From 64d32211bfa141d0cb218b592b2eee32651e66e8 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 9 Jan 2025 01:08:19 +0000 Subject: [PATCH 1/2] docs: fix comments of existing field PiperOrigin-RevId: 713414570 Source-Link: https://github.com/googleapis/googleapis/commit/ba1a1c7a863a59e2c3ce6d95eb25d1c546320446 Source-Link: https://github.com/googleapis/googleapis-gen/commit/5757850b48320202f8f8bfef54ba3915317b9e18 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWdrZS1tdWx0aWNsb3VkLy5Pd2xCb3QueWFtbCIsImgiOiI1NzU3ODUwYjQ4MzIwMjAyZjhmOGJmZWY1NGJhMzkxNTMxN2I5ZTE4In0= --- .../v1/.coveragerc | 13 + .../google-cloud-gke-multicloud/v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../google-cloud-gke-multicloud/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/conf.py | 376 + .../gke_multicloud_v1/attached_clusters.rst | 10 + .../docs/gke_multicloud_v1/aws_clusters.rst | 10 + .../docs/gke_multicloud_v1/azure_clusters.rst | 10 + .../v1/docs/gke_multicloud_v1/services_.rst | 8 + .../v1/docs/gke_multicloud_v1/types_.rst | 6 + .../v1/docs/index.rst | 7 + .../google/cloud/gke_multicloud/__init__.py | 299 + .../cloud/gke_multicloud/gapic_version.py | 16 + .../v1/google/cloud/gke_multicloud/py.typed | 2 + .../cloud/gke_multicloud_v1/__init__.py | 300 + .../gke_multicloud_v1/gapic_metadata.json | 726 + .../cloud/gke_multicloud_v1/gapic_version.py | 16 + .../google/cloud/gke_multicloud_v1/py.typed | 2 + .../gke_multicloud_v1/services/__init__.py | 15 + .../services/attached_clusters/__init__.py | 22 + .../attached_clusters/async_client.py | 1691 ++ .../services/attached_clusters/client.py | 2028 ++ .../services/attached_clusters/pagers.py | 167 + .../attached_clusters/transports/README.rst | 9 + .../attached_clusters/transports/__init__.py | 38 + .../attached_clusters/transports/base.py | 375 + .../attached_clusters/transports/grpc.py | 679 + .../transports/grpc_asyncio.py | 804 + .../attached_clusters/transports/rest.py | 2131 +++ .../attached_clusters/transports/rest_base.py | 562 + .../services/aws_clusters/__init__.py | 22 + .../services/aws_clusters/async_client.py | 2561 +++ .../services/aws_clusters/client.py | 2903 +++ .../services/aws_clusters/pagers.py | 306 + .../aws_clusters/transports/README.rst | 9 + .../aws_clusters/transports/__init__.py | 38 + .../services/aws_clusters/transports/base.py | 509 + .../services/aws_clusters/transports/grpc.py | 881 + .../aws_clusters/transports/grpc_asyncio.py | 1077 ++ .../services/aws_clusters/transports/rest.py | 3204 ++++ .../aws_clusters/transports/rest_base.py | 834 + .../services/azure_clusters/__init__.py | 22 + .../services/azure_clusters/async_client.py | 3034 +++ .../services/azure_clusters/client.py | 3380 ++++ .../services/azure_clusters/pagers.py | 445 + .../azure_clusters/transports/README.rst | 9 + .../azure_clusters/transports/__init__.py | 38 + .../azure_clusters/transports/base.py | 569 + .../azure_clusters/transports/grpc.py | 981 + .../azure_clusters/transports/grpc_asyncio.py | 1210 ++ .../azure_clusters/transports/rest.py | 3678 ++++ .../azure_clusters/transports/rest_base.py | 942 + .../cloud/gke_multicloud_v1/types/__init__.py | 296 + .../types/attached_resources.py | 505 + .../types/attached_service.py | 574 + .../gke_multicloud_v1/types/aws_resources.py | 1424 ++ .../gke_multicloud_v1/types/aws_service.py | 850 + .../types/azure_resources.py | 1398 ++ .../gke_multicloud_v1/types/azure_service.py | 986 + .../types/common_resources.py | 576 + .../google-cloud-gke-multicloud/v1/mypy.ini | 3 + .../google-cloud-gke-multicloud/v1/noxfile.py | 280 + ..._clusters_create_attached_cluster_async.py | 63 + ...d_clusters_create_attached_cluster_sync.py | 63 + ..._clusters_delete_attached_cluster_async.py | 56 + ...d_clusters_delete_attached_cluster_sync.py | 56 + ...rate_attached_cluster_agent_token_async.py | 55 + ...erate_attached_cluster_agent_token_sync.py | 55 + ...attached_cluster_install_manifest_async.py | 54 + ..._attached_cluster_install_manifest_sync.py | 54 + ...hed_clusters_get_attached_cluster_async.py | 52 + ...ched_clusters_get_attached_cluster_sync.py | 52 + ...usters_get_attached_server_config_async.py | 52 + ...lusters_get_attached_server_config_sync.py | 52 + ..._clusters_import_attached_cluster_async.py | 59 + ...d_clusters_import_attached_cluster_sync.py | 59 + ...d_clusters_list_attached_clusters_async.py | 53 + ...ed_clusters_list_attached_clusters_sync.py | 53 + ..._clusters_update_attached_cluster_async.py | 61 + ...d_clusters_update_attached_cluster_sync.py | 61 + ...d_aws_clusters_create_aws_cluster_async.py | 71 + ...ed_aws_clusters_create_aws_cluster_sync.py | 71 + ...aws_clusters_create_aws_node_pool_async.py | 67 + ..._aws_clusters_create_aws_node_pool_sync.py | 67 + ...d_aws_clusters_delete_aws_cluster_async.py | 56 + ...ed_aws_clusters_delete_aws_cluster_sync.py | 56 + ...aws_clusters_delete_aws_node_pool_async.py | 56 + ..._aws_clusters_delete_aws_node_pool_sync.py | 56 + ...lusters_generate_aws_access_token_async.py | 52 + ...clusters_generate_aws_access_token_sync.py | 52 + ..._generate_aws_cluster_agent_token_async.py | 55 + ...s_generate_aws_cluster_agent_token_sync.py | 55 + ...ated_aws_clusters_get_aws_cluster_async.py | 52 + ...rated_aws_clusters_get_aws_cluster_sync.py | 52 + ...ws_clusters_get_aws_json_web_keys_async.py | 52 + ...aws_clusters_get_aws_json_web_keys_sync.py | 52 + ...ed_aws_clusters_get_aws_node_pool_async.py | 52 + ...ted_aws_clusters_get_aws_node_pool_sync.py | 52 + ...s_clusters_get_aws_open_id_config_async.py | 52 + ...ws_clusters_get_aws_open_id_config_sync.py | 52 + ...ws_clusters_get_aws_server_config_async.py | 52 + ...aws_clusters_get_aws_server_config_sync.py | 52 + ...ed_aws_clusters_list_aws_clusters_async.py | 53 + ...ted_aws_clusters_list_aws_clusters_sync.py | 53 + ..._aws_clusters_list_aws_node_pools_async.py | 53 + ...d_aws_clusters_list_aws_node_pools_sync.py | 53 + ...ers_rollback_aws_node_pool_update_async.py | 56 + ...ters_rollback_aws_node_pool_update_sync.py | 56 + ...d_aws_clusters_update_aws_cluster_async.py | 69 + ...ed_aws_clusters_update_aws_cluster_sync.py | 69 + ...aws_clusters_update_aws_node_pool_async.py | 65 + ..._aws_clusters_update_aws_node_pool_sync.py | 65 + ...zure_clusters_create_azure_client_async.py | 62 + ...azure_clusters_create_azure_client_sync.py | 62 + ...ure_clusters_create_azure_cluster_async.py | 68 + ...zure_clusters_create_azure_cluster_sync.py | 68 + ...e_clusters_create_azure_node_pool_async.py | 66 + ...re_clusters_create_azure_node_pool_sync.py | 66 + ...zure_clusters_delete_azure_client_async.py | 56 + ...azure_clusters_delete_azure_client_sync.py | 56 + ...ure_clusters_delete_azure_cluster_async.py | 56 + ...zure_clusters_delete_azure_cluster_sync.py | 56 + ...e_clusters_delete_azure_node_pool_async.py | 56 + ...re_clusters_delete_azure_node_pool_sync.py | 56 + ...sters_generate_azure_access_token_async.py | 52 + ...usters_generate_azure_access_token_sync.py | 52 + ...enerate_azure_cluster_agent_token_async.py | 55 + ...generate_azure_cluster_agent_token_sync.py | 55 + ...d_azure_clusters_get_azure_client_async.py | 52 + ...ed_azure_clusters_get_azure_client_sync.py | 52 + ..._azure_clusters_get_azure_cluster_async.py | 52 + ...d_azure_clusters_get_azure_cluster_sync.py | 52 + ..._clusters_get_azure_json_web_keys_async.py | 52 + ...e_clusters_get_azure_json_web_keys_sync.py | 52 + ...zure_clusters_get_azure_node_pool_async.py | 52 + ...azure_clusters_get_azure_node_pool_sync.py | 52 + ...clusters_get_azure_open_id_config_async.py | 52 + ..._clusters_get_azure_open_id_config_sync.py | 52 + ..._clusters_get_azure_server_config_async.py | 52 + ...e_clusters_get_azure_server_config_sync.py | 52 + ...azure_clusters_list_azure_clients_async.py | 53 + ..._azure_clusters_list_azure_clients_sync.py | 53 + ...zure_clusters_list_azure_clusters_async.py | 53 + ...azure_clusters_list_azure_clusters_sync.py | 53 + ...re_clusters_list_azure_node_pools_async.py | 53 + ...ure_clusters_list_azure_node_pools_sync.py | 53 + ...ure_clusters_update_azure_cluster_async.py | 66 + ...zure_clusters_update_azure_cluster_sync.py | 66 + ...e_clusters_update_azure_node_pool_async.py | 64 + ...re_clusters_update_azure_node_pool_sync.py | 64 + ...etadata_google.cloud.gkemulticloud.v1.json | 7195 +++++++ .../fixup_gke_multicloud_v1_keywords.py | 219 + .../google-cloud-gke-multicloud/v1/setup.py | 98 + .../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.13.txt | 6 + .../v1/testing/constraints-3.7.txt | 10 + .../v1/testing/constraints-3.8.txt | 6 + .../v1/testing/constraints-3.9.txt | 6 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/gke_multicloud_v1/__init__.py | 16 + .../test_attached_clusters.py | 8616 +++++++++ .../gke_multicloud_v1/test_aws_clusters.py | 13259 +++++++++++++ .../gke_multicloud_v1/test_azure_clusters.py | 15936 ++++++++++++++++ 168 files changed, 94366 insertions(+) create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/attached_clusters.rst create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/aws_clusters.rst create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/azure_clusters.rst create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/py.typed create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/async_client.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/client.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/pagers.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/base.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/async_client.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/client.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/pagers.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/base.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/async_client.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/client.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/pagers.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/base.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_resources.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_service.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_resources.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_service.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_resources.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_service.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/common_resources.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/scripts/fixup_gke_multicloud_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_attached_clusters.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_aws_clusters.py create mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_azure_clusters.py diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/.coveragerc b/owl-bot-staging/google-cloud-gke-multicloud/v1/.coveragerc new file mode 100644 index 000000000000..5e02aeaf7a3a --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/gke_multicloud/__init__.py + google/cloud/gke_multicloud/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/.flake8 b/owl-bot-staging/google-cloud-gke-multicloud/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/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/google-cloud-gke-multicloud/v1/MANIFEST.in b/owl-bot-staging/google-cloud-gke-multicloud/v1/MANIFEST.in new file mode 100644 index 000000000000..bfb6acf0cc1b --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/gke_multicloud *.py +recursive-include google/cloud/gke_multicloud_v1 *.py diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/README.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/README.rst new file mode 100644 index 000000000000..9819c2326735 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Gke Multicloud 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 Gke Multicloud API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/conf.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/conf.py new file mode 100644 index 000000000000..caf1acccc968 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-gke-multicloud 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-multicloud" +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-multicloud-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-multicloud.tex", + u"google-cloud-gke-multicloud 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-multicloud", + u"Google Cloud Gke Multicloud 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-multicloud", + u"google-cloud-gke-multicloud Documentation", + author, + "google-cloud-gke-multicloud", + "GAPIC library for Google Cloud Gke Multicloud API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/attached_clusters.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/attached_clusters.rst new file mode 100644 index 000000000000..b5ef09045bc5 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/attached_clusters.rst @@ -0,0 +1,10 @@ +AttachedClusters +---------------------------------- + +.. automodule:: google.cloud.gke_multicloud_v1.services.attached_clusters + :members: + :inherited-members: + +.. automodule:: google.cloud.gke_multicloud_v1.services.attached_clusters.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/aws_clusters.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/aws_clusters.rst new file mode 100644 index 000000000000..3c6c464c9735 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/aws_clusters.rst @@ -0,0 +1,10 @@ +AwsClusters +----------------------------- + +.. automodule:: google.cloud.gke_multicloud_v1.services.aws_clusters + :members: + :inherited-members: + +.. automodule:: google.cloud.gke_multicloud_v1.services.aws_clusters.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/azure_clusters.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/azure_clusters.rst new file mode 100644 index 000000000000..2ba97619d4ce --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/azure_clusters.rst @@ -0,0 +1,10 @@ +AzureClusters +------------------------------- + +.. automodule:: google.cloud.gke_multicloud_v1.services.azure_clusters + :members: + :inherited-members: + +.. automodule:: google.cloud.gke_multicloud_v1.services.azure_clusters.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/services_.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/services_.rst new file mode 100644 index 000000000000..6f2ba1f59ab4 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/services_.rst @@ -0,0 +1,8 @@ +Services for Google Cloud Gke Multicloud v1 API +=============================================== +.. toctree:: + :maxdepth: 2 + + attached_clusters + aws_clusters + azure_clusters diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/types_.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/types_.rst new file mode 100644 index 000000000000..e98b40dbb745 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Gke Multicloud v1 API +============================================ + +.. automodule:: google.cloud.gke_multicloud_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/index.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/index.rst new file mode 100644 index 000000000000..306bfc21e2b0 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + gke_multicloud_v1/services_ + gke_multicloud_v1/types_ diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/__init__.py new file mode 100644 index 000000000000..08a8a2fd4d39 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/__init__.py @@ -0,0 +1,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.gke_multicloud import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.gke_multicloud_v1.services.attached_clusters.client import AttachedClustersClient +from google.cloud.gke_multicloud_v1.services.attached_clusters.async_client import AttachedClustersAsyncClient +from google.cloud.gke_multicloud_v1.services.aws_clusters.client import AwsClustersClient +from google.cloud.gke_multicloud_v1.services.aws_clusters.async_client import AwsClustersAsyncClient +from google.cloud.gke_multicloud_v1.services.azure_clusters.client import AzureClustersClient +from google.cloud.gke_multicloud_v1.services.azure_clusters.async_client import AzureClustersAsyncClient + +from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedCluster +from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedClusterError +from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedClusterGroup +from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedClustersAuthorization +from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedClusterUser +from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedOidcConfig +from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedPlatformVersionInfo +from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedProxyConfig +from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedServerConfig +from google.cloud.gke_multicloud_v1.types.attached_resources import KubernetesSecret +from google.cloud.gke_multicloud_v1.types.attached_service import CreateAttachedClusterRequest +from google.cloud.gke_multicloud_v1.types.attached_service import DeleteAttachedClusterRequest +from google.cloud.gke_multicloud_v1.types.attached_service import GenerateAttachedClusterAgentTokenRequest +from google.cloud.gke_multicloud_v1.types.attached_service import GenerateAttachedClusterAgentTokenResponse +from google.cloud.gke_multicloud_v1.types.attached_service import GenerateAttachedClusterInstallManifestRequest +from google.cloud.gke_multicloud_v1.types.attached_service import GenerateAttachedClusterInstallManifestResponse +from google.cloud.gke_multicloud_v1.types.attached_service import GetAttachedClusterRequest +from google.cloud.gke_multicloud_v1.types.attached_service import GetAttachedServerConfigRequest +from google.cloud.gke_multicloud_v1.types.attached_service import ImportAttachedClusterRequest +from google.cloud.gke_multicloud_v1.types.attached_service import ListAttachedClustersRequest +from google.cloud.gke_multicloud_v1.types.attached_service import ListAttachedClustersResponse +from google.cloud.gke_multicloud_v1.types.attached_service import UpdateAttachedClusterRequest +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsAuthorization +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsAutoscalingGroupMetricsCollection +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsCluster +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsClusterError +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsClusterGroup +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsClusterNetworking +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsClusterUser +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsConfigEncryption +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsControlPlane +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsDatabaseEncryption +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsInstancePlacement +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsJsonWebKeys +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsK8sVersionInfo +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsNodeConfig +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsNodeManagement +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsNodePool +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsNodePoolAutoscaling +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsNodePoolError +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsOpenIdConfig +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsProxyConfig +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsServerConfig +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsServicesAuthentication +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsSshConfig +from google.cloud.gke_multicloud_v1.types.aws_resources import AwsVolumeTemplate +from google.cloud.gke_multicloud_v1.types.aws_resources import SpotConfig +from google.cloud.gke_multicloud_v1.types.aws_resources import SurgeSettings +from google.cloud.gke_multicloud_v1.types.aws_resources import UpdateSettings +from google.cloud.gke_multicloud_v1.types.aws_service import CreateAwsClusterRequest +from google.cloud.gke_multicloud_v1.types.aws_service import CreateAwsNodePoolRequest +from google.cloud.gke_multicloud_v1.types.aws_service import DeleteAwsClusterRequest +from google.cloud.gke_multicloud_v1.types.aws_service import DeleteAwsNodePoolRequest +from google.cloud.gke_multicloud_v1.types.aws_service import GenerateAwsAccessTokenRequest +from google.cloud.gke_multicloud_v1.types.aws_service import GenerateAwsAccessTokenResponse +from google.cloud.gke_multicloud_v1.types.aws_service import GenerateAwsClusterAgentTokenRequest +from google.cloud.gke_multicloud_v1.types.aws_service import GenerateAwsClusterAgentTokenResponse +from google.cloud.gke_multicloud_v1.types.aws_service import GetAwsClusterRequest +from google.cloud.gke_multicloud_v1.types.aws_service import GetAwsJsonWebKeysRequest +from google.cloud.gke_multicloud_v1.types.aws_service import GetAwsNodePoolRequest +from google.cloud.gke_multicloud_v1.types.aws_service import GetAwsOpenIdConfigRequest +from google.cloud.gke_multicloud_v1.types.aws_service import GetAwsServerConfigRequest +from google.cloud.gke_multicloud_v1.types.aws_service import ListAwsClustersRequest +from google.cloud.gke_multicloud_v1.types.aws_service import ListAwsClustersResponse +from google.cloud.gke_multicloud_v1.types.aws_service import ListAwsNodePoolsRequest +from google.cloud.gke_multicloud_v1.types.aws_service import ListAwsNodePoolsResponse +from google.cloud.gke_multicloud_v1.types.aws_service import RollbackAwsNodePoolUpdateRequest +from google.cloud.gke_multicloud_v1.types.aws_service import UpdateAwsClusterRequest +from google.cloud.gke_multicloud_v1.types.aws_service import UpdateAwsNodePoolRequest +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureAuthorization +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClient +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureCluster +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClusterError +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClusterGroup +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClusterNetworking +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClusterResources +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClusterUser +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureConfigEncryption +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureControlPlane +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureDatabaseEncryption +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureDiskTemplate +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureJsonWebKeys +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureK8sVersionInfo +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureNodeConfig +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureNodeManagement +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureNodePool +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureNodePoolAutoscaling +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureNodePoolError +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureOpenIdConfig +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureProxyConfig +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureServerConfig +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureServicesAuthentication +from google.cloud.gke_multicloud_v1.types.azure_resources import AzureSshConfig +from google.cloud.gke_multicloud_v1.types.azure_resources import ReplicaPlacement +from google.cloud.gke_multicloud_v1.types.azure_service import CreateAzureClientRequest +from google.cloud.gke_multicloud_v1.types.azure_service import CreateAzureClusterRequest +from google.cloud.gke_multicloud_v1.types.azure_service import CreateAzureNodePoolRequest +from google.cloud.gke_multicloud_v1.types.azure_service import DeleteAzureClientRequest +from google.cloud.gke_multicloud_v1.types.azure_service import DeleteAzureClusterRequest +from google.cloud.gke_multicloud_v1.types.azure_service import DeleteAzureNodePoolRequest +from google.cloud.gke_multicloud_v1.types.azure_service import GenerateAzureAccessTokenRequest +from google.cloud.gke_multicloud_v1.types.azure_service import GenerateAzureAccessTokenResponse +from google.cloud.gke_multicloud_v1.types.azure_service import GenerateAzureClusterAgentTokenRequest +from google.cloud.gke_multicloud_v1.types.azure_service import GenerateAzureClusterAgentTokenResponse +from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureClientRequest +from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureClusterRequest +from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureJsonWebKeysRequest +from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureNodePoolRequest +from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureOpenIdConfigRequest +from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureServerConfigRequest +from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureClientsRequest +from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureClientsResponse +from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureClustersRequest +from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureClustersResponse +from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureNodePoolsRequest +from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureNodePoolsResponse +from google.cloud.gke_multicloud_v1.types.azure_service import UpdateAzureClusterRequest +from google.cloud.gke_multicloud_v1.types.azure_service import UpdateAzureNodePoolRequest +from google.cloud.gke_multicloud_v1.types.common_resources import BinaryAuthorization +from google.cloud.gke_multicloud_v1.types.common_resources import CloudMonitoringConfig +from google.cloud.gke_multicloud_v1.types.common_resources import Fleet +from google.cloud.gke_multicloud_v1.types.common_resources import Jwk +from google.cloud.gke_multicloud_v1.types.common_resources import LoggingComponentConfig +from google.cloud.gke_multicloud_v1.types.common_resources import LoggingConfig +from google.cloud.gke_multicloud_v1.types.common_resources import ManagedPrometheusConfig +from google.cloud.gke_multicloud_v1.types.common_resources import MaxPodsConstraint +from google.cloud.gke_multicloud_v1.types.common_resources import MonitoringConfig +from google.cloud.gke_multicloud_v1.types.common_resources import NodeKubeletConfig +from google.cloud.gke_multicloud_v1.types.common_resources import NodeTaint +from google.cloud.gke_multicloud_v1.types.common_resources import OperationMetadata +from google.cloud.gke_multicloud_v1.types.common_resources import SecurityPostureConfig +from google.cloud.gke_multicloud_v1.types.common_resources import WorkloadIdentityConfig + +__all__ = ('AttachedClustersClient', + 'AttachedClustersAsyncClient', + 'AwsClustersClient', + 'AwsClustersAsyncClient', + 'AzureClustersClient', + 'AzureClustersAsyncClient', + 'AttachedCluster', + 'AttachedClusterError', + 'AttachedClusterGroup', + 'AttachedClustersAuthorization', + 'AttachedClusterUser', + 'AttachedOidcConfig', + 'AttachedPlatformVersionInfo', + 'AttachedProxyConfig', + 'AttachedServerConfig', + 'KubernetesSecret', + 'CreateAttachedClusterRequest', + 'DeleteAttachedClusterRequest', + 'GenerateAttachedClusterAgentTokenRequest', + 'GenerateAttachedClusterAgentTokenResponse', + 'GenerateAttachedClusterInstallManifestRequest', + 'GenerateAttachedClusterInstallManifestResponse', + 'GetAttachedClusterRequest', + 'GetAttachedServerConfigRequest', + 'ImportAttachedClusterRequest', + 'ListAttachedClustersRequest', + 'ListAttachedClustersResponse', + 'UpdateAttachedClusterRequest', + 'AwsAuthorization', + 'AwsAutoscalingGroupMetricsCollection', + 'AwsCluster', + 'AwsClusterError', + 'AwsClusterGroup', + 'AwsClusterNetworking', + 'AwsClusterUser', + 'AwsConfigEncryption', + 'AwsControlPlane', + 'AwsDatabaseEncryption', + 'AwsInstancePlacement', + 'AwsJsonWebKeys', + 'AwsK8sVersionInfo', + 'AwsNodeConfig', + 'AwsNodeManagement', + 'AwsNodePool', + 'AwsNodePoolAutoscaling', + 'AwsNodePoolError', + 'AwsOpenIdConfig', + 'AwsProxyConfig', + 'AwsServerConfig', + 'AwsServicesAuthentication', + 'AwsSshConfig', + 'AwsVolumeTemplate', + 'SpotConfig', + 'SurgeSettings', + 'UpdateSettings', + 'CreateAwsClusterRequest', + 'CreateAwsNodePoolRequest', + 'DeleteAwsClusterRequest', + 'DeleteAwsNodePoolRequest', + 'GenerateAwsAccessTokenRequest', + 'GenerateAwsAccessTokenResponse', + 'GenerateAwsClusterAgentTokenRequest', + 'GenerateAwsClusterAgentTokenResponse', + 'GetAwsClusterRequest', + 'GetAwsJsonWebKeysRequest', + 'GetAwsNodePoolRequest', + 'GetAwsOpenIdConfigRequest', + 'GetAwsServerConfigRequest', + 'ListAwsClustersRequest', + 'ListAwsClustersResponse', + 'ListAwsNodePoolsRequest', + 'ListAwsNodePoolsResponse', + 'RollbackAwsNodePoolUpdateRequest', + 'UpdateAwsClusterRequest', + 'UpdateAwsNodePoolRequest', + 'AzureAuthorization', + 'AzureClient', + 'AzureCluster', + 'AzureClusterError', + 'AzureClusterGroup', + 'AzureClusterNetworking', + 'AzureClusterResources', + 'AzureClusterUser', + 'AzureConfigEncryption', + 'AzureControlPlane', + 'AzureDatabaseEncryption', + 'AzureDiskTemplate', + 'AzureJsonWebKeys', + 'AzureK8sVersionInfo', + 'AzureNodeConfig', + 'AzureNodeManagement', + 'AzureNodePool', + 'AzureNodePoolAutoscaling', + 'AzureNodePoolError', + 'AzureOpenIdConfig', + 'AzureProxyConfig', + 'AzureServerConfig', + 'AzureServicesAuthentication', + 'AzureSshConfig', + 'ReplicaPlacement', + 'CreateAzureClientRequest', + 'CreateAzureClusterRequest', + 'CreateAzureNodePoolRequest', + 'DeleteAzureClientRequest', + 'DeleteAzureClusterRequest', + 'DeleteAzureNodePoolRequest', + 'GenerateAzureAccessTokenRequest', + 'GenerateAzureAccessTokenResponse', + 'GenerateAzureClusterAgentTokenRequest', + 'GenerateAzureClusterAgentTokenResponse', + 'GetAzureClientRequest', + 'GetAzureClusterRequest', + 'GetAzureJsonWebKeysRequest', + 'GetAzureNodePoolRequest', + 'GetAzureOpenIdConfigRequest', + 'GetAzureServerConfigRequest', + 'ListAzureClientsRequest', + 'ListAzureClientsResponse', + 'ListAzureClustersRequest', + 'ListAzureClustersResponse', + 'ListAzureNodePoolsRequest', + 'ListAzureNodePoolsResponse', + 'UpdateAzureClusterRequest', + 'UpdateAzureNodePoolRequest', + 'BinaryAuthorization', + 'CloudMonitoringConfig', + 'Fleet', + 'Jwk', + 'LoggingComponentConfig', + 'LoggingConfig', + 'ManagedPrometheusConfig', + 'MaxPodsConstraint', + 'MonitoringConfig', + 'NodeKubeletConfig', + 'NodeTaint', + 'OperationMetadata', + 'SecurityPostureConfig', + 'WorkloadIdentityConfig', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/gapic_version.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/py.typed b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/py.typed new file mode 100644 index 000000000000..53546ad8d1e7 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gke-multicloud package uses inline types. diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/__init__.py new file mode 100644 index 000000000000..e62d46fa024e --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/__init__.py @@ -0,0 +1,300 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.gke_multicloud_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.attached_clusters import AttachedClustersClient +from .services.attached_clusters import AttachedClustersAsyncClient +from .services.aws_clusters import AwsClustersClient +from .services.aws_clusters import AwsClustersAsyncClient +from .services.azure_clusters import AzureClustersClient +from .services.azure_clusters import AzureClustersAsyncClient + +from .types.attached_resources import AttachedCluster +from .types.attached_resources import AttachedClusterError +from .types.attached_resources import AttachedClusterGroup +from .types.attached_resources import AttachedClustersAuthorization +from .types.attached_resources import AttachedClusterUser +from .types.attached_resources import AttachedOidcConfig +from .types.attached_resources import AttachedPlatformVersionInfo +from .types.attached_resources import AttachedProxyConfig +from .types.attached_resources import AttachedServerConfig +from .types.attached_resources import KubernetesSecret +from .types.attached_service import CreateAttachedClusterRequest +from .types.attached_service import DeleteAttachedClusterRequest +from .types.attached_service import GenerateAttachedClusterAgentTokenRequest +from .types.attached_service import GenerateAttachedClusterAgentTokenResponse +from .types.attached_service import GenerateAttachedClusterInstallManifestRequest +from .types.attached_service import GenerateAttachedClusterInstallManifestResponse +from .types.attached_service import GetAttachedClusterRequest +from .types.attached_service import GetAttachedServerConfigRequest +from .types.attached_service import ImportAttachedClusterRequest +from .types.attached_service import ListAttachedClustersRequest +from .types.attached_service import ListAttachedClustersResponse +from .types.attached_service import UpdateAttachedClusterRequest +from .types.aws_resources import AwsAuthorization +from .types.aws_resources import AwsAutoscalingGroupMetricsCollection +from .types.aws_resources import AwsCluster +from .types.aws_resources import AwsClusterError +from .types.aws_resources import AwsClusterGroup +from .types.aws_resources import AwsClusterNetworking +from .types.aws_resources import AwsClusterUser +from .types.aws_resources import AwsConfigEncryption +from .types.aws_resources import AwsControlPlane +from .types.aws_resources import AwsDatabaseEncryption +from .types.aws_resources import AwsInstancePlacement +from .types.aws_resources import AwsJsonWebKeys +from .types.aws_resources import AwsK8sVersionInfo +from .types.aws_resources import AwsNodeConfig +from .types.aws_resources import AwsNodeManagement +from .types.aws_resources import AwsNodePool +from .types.aws_resources import AwsNodePoolAutoscaling +from .types.aws_resources import AwsNodePoolError +from .types.aws_resources import AwsOpenIdConfig +from .types.aws_resources import AwsProxyConfig +from .types.aws_resources import AwsServerConfig +from .types.aws_resources import AwsServicesAuthentication +from .types.aws_resources import AwsSshConfig +from .types.aws_resources import AwsVolumeTemplate +from .types.aws_resources import SpotConfig +from .types.aws_resources import SurgeSettings +from .types.aws_resources import UpdateSettings +from .types.aws_service import CreateAwsClusterRequest +from .types.aws_service import CreateAwsNodePoolRequest +from .types.aws_service import DeleteAwsClusterRequest +from .types.aws_service import DeleteAwsNodePoolRequest +from .types.aws_service import GenerateAwsAccessTokenRequest +from .types.aws_service import GenerateAwsAccessTokenResponse +from .types.aws_service import GenerateAwsClusterAgentTokenRequest +from .types.aws_service import GenerateAwsClusterAgentTokenResponse +from .types.aws_service import GetAwsClusterRequest +from .types.aws_service import GetAwsJsonWebKeysRequest +from .types.aws_service import GetAwsNodePoolRequest +from .types.aws_service import GetAwsOpenIdConfigRequest +from .types.aws_service import GetAwsServerConfigRequest +from .types.aws_service import ListAwsClustersRequest +from .types.aws_service import ListAwsClustersResponse +from .types.aws_service import ListAwsNodePoolsRequest +from .types.aws_service import ListAwsNodePoolsResponse +from .types.aws_service import RollbackAwsNodePoolUpdateRequest +from .types.aws_service import UpdateAwsClusterRequest +from .types.aws_service import UpdateAwsNodePoolRequest +from .types.azure_resources import AzureAuthorization +from .types.azure_resources import AzureClient +from .types.azure_resources import AzureCluster +from .types.azure_resources import AzureClusterError +from .types.azure_resources import AzureClusterGroup +from .types.azure_resources import AzureClusterNetworking +from .types.azure_resources import AzureClusterResources +from .types.azure_resources import AzureClusterUser +from .types.azure_resources import AzureConfigEncryption +from .types.azure_resources import AzureControlPlane +from .types.azure_resources import AzureDatabaseEncryption +from .types.azure_resources import AzureDiskTemplate +from .types.azure_resources import AzureJsonWebKeys +from .types.azure_resources import AzureK8sVersionInfo +from .types.azure_resources import AzureNodeConfig +from .types.azure_resources import AzureNodeManagement +from .types.azure_resources import AzureNodePool +from .types.azure_resources import AzureNodePoolAutoscaling +from .types.azure_resources import AzureNodePoolError +from .types.azure_resources import AzureOpenIdConfig +from .types.azure_resources import AzureProxyConfig +from .types.azure_resources import AzureServerConfig +from .types.azure_resources import AzureServicesAuthentication +from .types.azure_resources import AzureSshConfig +from .types.azure_resources import ReplicaPlacement +from .types.azure_service import CreateAzureClientRequest +from .types.azure_service import CreateAzureClusterRequest +from .types.azure_service import CreateAzureNodePoolRequest +from .types.azure_service import DeleteAzureClientRequest +from .types.azure_service import DeleteAzureClusterRequest +from .types.azure_service import DeleteAzureNodePoolRequest +from .types.azure_service import GenerateAzureAccessTokenRequest +from .types.azure_service import GenerateAzureAccessTokenResponse +from .types.azure_service import GenerateAzureClusterAgentTokenRequest +from .types.azure_service import GenerateAzureClusterAgentTokenResponse +from .types.azure_service import GetAzureClientRequest +from .types.azure_service import GetAzureClusterRequest +from .types.azure_service import GetAzureJsonWebKeysRequest +from .types.azure_service import GetAzureNodePoolRequest +from .types.azure_service import GetAzureOpenIdConfigRequest +from .types.azure_service import GetAzureServerConfigRequest +from .types.azure_service import ListAzureClientsRequest +from .types.azure_service import ListAzureClientsResponse +from .types.azure_service import ListAzureClustersRequest +from .types.azure_service import ListAzureClustersResponse +from .types.azure_service import ListAzureNodePoolsRequest +from .types.azure_service import ListAzureNodePoolsResponse +from .types.azure_service import UpdateAzureClusterRequest +from .types.azure_service import UpdateAzureNodePoolRequest +from .types.common_resources import BinaryAuthorization +from .types.common_resources import CloudMonitoringConfig +from .types.common_resources import Fleet +from .types.common_resources import Jwk +from .types.common_resources import LoggingComponentConfig +from .types.common_resources import LoggingConfig +from .types.common_resources import ManagedPrometheusConfig +from .types.common_resources import MaxPodsConstraint +from .types.common_resources import MonitoringConfig +from .types.common_resources import NodeKubeletConfig +from .types.common_resources import NodeTaint +from .types.common_resources import OperationMetadata +from .types.common_resources import SecurityPostureConfig +from .types.common_resources import WorkloadIdentityConfig + +__all__ = ( + 'AttachedClustersAsyncClient', + 'AwsClustersAsyncClient', + 'AzureClustersAsyncClient', +'AttachedCluster', +'AttachedClusterError', +'AttachedClusterGroup', +'AttachedClusterUser', +'AttachedClustersAuthorization', +'AttachedClustersClient', +'AttachedOidcConfig', +'AttachedPlatformVersionInfo', +'AttachedProxyConfig', +'AttachedServerConfig', +'AwsAuthorization', +'AwsAutoscalingGroupMetricsCollection', +'AwsCluster', +'AwsClusterError', +'AwsClusterGroup', +'AwsClusterNetworking', +'AwsClusterUser', +'AwsClustersClient', +'AwsConfigEncryption', +'AwsControlPlane', +'AwsDatabaseEncryption', +'AwsInstancePlacement', +'AwsJsonWebKeys', +'AwsK8sVersionInfo', +'AwsNodeConfig', +'AwsNodeManagement', +'AwsNodePool', +'AwsNodePoolAutoscaling', +'AwsNodePoolError', +'AwsOpenIdConfig', +'AwsProxyConfig', +'AwsServerConfig', +'AwsServicesAuthentication', +'AwsSshConfig', +'AwsVolumeTemplate', +'AzureAuthorization', +'AzureClient', +'AzureCluster', +'AzureClusterError', +'AzureClusterGroup', +'AzureClusterNetworking', +'AzureClusterResources', +'AzureClusterUser', +'AzureClustersClient', +'AzureConfigEncryption', +'AzureControlPlane', +'AzureDatabaseEncryption', +'AzureDiskTemplate', +'AzureJsonWebKeys', +'AzureK8sVersionInfo', +'AzureNodeConfig', +'AzureNodeManagement', +'AzureNodePool', +'AzureNodePoolAutoscaling', +'AzureNodePoolError', +'AzureOpenIdConfig', +'AzureProxyConfig', +'AzureServerConfig', +'AzureServicesAuthentication', +'AzureSshConfig', +'BinaryAuthorization', +'CloudMonitoringConfig', +'CreateAttachedClusterRequest', +'CreateAwsClusterRequest', +'CreateAwsNodePoolRequest', +'CreateAzureClientRequest', +'CreateAzureClusterRequest', +'CreateAzureNodePoolRequest', +'DeleteAttachedClusterRequest', +'DeleteAwsClusterRequest', +'DeleteAwsNodePoolRequest', +'DeleteAzureClientRequest', +'DeleteAzureClusterRequest', +'DeleteAzureNodePoolRequest', +'Fleet', +'GenerateAttachedClusterAgentTokenRequest', +'GenerateAttachedClusterAgentTokenResponse', +'GenerateAttachedClusterInstallManifestRequest', +'GenerateAttachedClusterInstallManifestResponse', +'GenerateAwsAccessTokenRequest', +'GenerateAwsAccessTokenResponse', +'GenerateAwsClusterAgentTokenRequest', +'GenerateAwsClusterAgentTokenResponse', +'GenerateAzureAccessTokenRequest', +'GenerateAzureAccessTokenResponse', +'GenerateAzureClusterAgentTokenRequest', +'GenerateAzureClusterAgentTokenResponse', +'GetAttachedClusterRequest', +'GetAttachedServerConfigRequest', +'GetAwsClusterRequest', +'GetAwsJsonWebKeysRequest', +'GetAwsNodePoolRequest', +'GetAwsOpenIdConfigRequest', +'GetAwsServerConfigRequest', +'GetAzureClientRequest', +'GetAzureClusterRequest', +'GetAzureJsonWebKeysRequest', +'GetAzureNodePoolRequest', +'GetAzureOpenIdConfigRequest', +'GetAzureServerConfigRequest', +'ImportAttachedClusterRequest', +'Jwk', +'KubernetesSecret', +'ListAttachedClustersRequest', +'ListAttachedClustersResponse', +'ListAwsClustersRequest', +'ListAwsClustersResponse', +'ListAwsNodePoolsRequest', +'ListAwsNodePoolsResponse', +'ListAzureClientsRequest', +'ListAzureClientsResponse', +'ListAzureClustersRequest', +'ListAzureClustersResponse', +'ListAzureNodePoolsRequest', +'ListAzureNodePoolsResponse', +'LoggingComponentConfig', +'LoggingConfig', +'ManagedPrometheusConfig', +'MaxPodsConstraint', +'MonitoringConfig', +'NodeKubeletConfig', +'NodeTaint', +'OperationMetadata', +'ReplicaPlacement', +'RollbackAwsNodePoolUpdateRequest', +'SecurityPostureConfig', +'SpotConfig', +'SurgeSettings', +'UpdateAttachedClusterRequest', +'UpdateAwsClusterRequest', +'UpdateAwsNodePoolRequest', +'UpdateAzureClusterRequest', +'UpdateAzureNodePoolRequest', +'UpdateSettings', +'WorkloadIdentityConfig', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_metadata.json new file mode 100644 index 000000000000..544cf3260044 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_metadata.json @@ -0,0 +1,726 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.gke_multicloud_v1", + "protoPackage": "google.cloud.gkemulticloud.v1", + "schema": "1.0", + "services": { + "AttachedClusters": { + "clients": { + "grpc": { + "libraryClient": "AttachedClustersClient", + "rpcs": { + "CreateAttachedCluster": { + "methods": [ + "create_attached_cluster" + ] + }, + "DeleteAttachedCluster": { + "methods": [ + "delete_attached_cluster" + ] + }, + "GenerateAttachedClusterAgentToken": { + "methods": [ + "generate_attached_cluster_agent_token" + ] + }, + "GenerateAttachedClusterInstallManifest": { + "methods": [ + "generate_attached_cluster_install_manifest" + ] + }, + "GetAttachedCluster": { + "methods": [ + "get_attached_cluster" + ] + }, + "GetAttachedServerConfig": { + "methods": [ + "get_attached_server_config" + ] + }, + "ImportAttachedCluster": { + "methods": [ + "import_attached_cluster" + ] + }, + "ListAttachedClusters": { + "methods": [ + "list_attached_clusters" + ] + }, + "UpdateAttachedCluster": { + "methods": [ + "update_attached_cluster" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AttachedClustersAsyncClient", + "rpcs": { + "CreateAttachedCluster": { + "methods": [ + "create_attached_cluster" + ] + }, + "DeleteAttachedCluster": { + "methods": [ + "delete_attached_cluster" + ] + }, + "GenerateAttachedClusterAgentToken": { + "methods": [ + "generate_attached_cluster_agent_token" + ] + }, + "GenerateAttachedClusterInstallManifest": { + "methods": [ + "generate_attached_cluster_install_manifest" + ] + }, + "GetAttachedCluster": { + "methods": [ + "get_attached_cluster" + ] + }, + "GetAttachedServerConfig": { + "methods": [ + "get_attached_server_config" + ] + }, + "ImportAttachedCluster": { + "methods": [ + "import_attached_cluster" + ] + }, + "ListAttachedClusters": { + "methods": [ + "list_attached_clusters" + ] + }, + "UpdateAttachedCluster": { + "methods": [ + "update_attached_cluster" + ] + } + } + }, + "rest": { + "libraryClient": "AttachedClustersClient", + "rpcs": { + "CreateAttachedCluster": { + "methods": [ + "create_attached_cluster" + ] + }, + "DeleteAttachedCluster": { + "methods": [ + "delete_attached_cluster" + ] + }, + "GenerateAttachedClusterAgentToken": { + "methods": [ + "generate_attached_cluster_agent_token" + ] + }, + "GenerateAttachedClusterInstallManifest": { + "methods": [ + "generate_attached_cluster_install_manifest" + ] + }, + "GetAttachedCluster": { + "methods": [ + "get_attached_cluster" + ] + }, + "GetAttachedServerConfig": { + "methods": [ + "get_attached_server_config" + ] + }, + "ImportAttachedCluster": { + "methods": [ + "import_attached_cluster" + ] + }, + "ListAttachedClusters": { + "methods": [ + "list_attached_clusters" + ] + }, + "UpdateAttachedCluster": { + "methods": [ + "update_attached_cluster" + ] + } + } + } + } + }, + "AwsClusters": { + "clients": { + "grpc": { + "libraryClient": "AwsClustersClient", + "rpcs": { + "CreateAwsCluster": { + "methods": [ + "create_aws_cluster" + ] + }, + "CreateAwsNodePool": { + "methods": [ + "create_aws_node_pool" + ] + }, + "DeleteAwsCluster": { + "methods": [ + "delete_aws_cluster" + ] + }, + "DeleteAwsNodePool": { + "methods": [ + "delete_aws_node_pool" + ] + }, + "GenerateAwsAccessToken": { + "methods": [ + "generate_aws_access_token" + ] + }, + "GenerateAwsClusterAgentToken": { + "methods": [ + "generate_aws_cluster_agent_token" + ] + }, + "GetAwsCluster": { + "methods": [ + "get_aws_cluster" + ] + }, + "GetAwsJsonWebKeys": { + "methods": [ + "get_aws_json_web_keys" + ] + }, + "GetAwsNodePool": { + "methods": [ + "get_aws_node_pool" + ] + }, + "GetAwsOpenIdConfig": { + "methods": [ + "get_aws_open_id_config" + ] + }, + "GetAwsServerConfig": { + "methods": [ + "get_aws_server_config" + ] + }, + "ListAwsClusters": { + "methods": [ + "list_aws_clusters" + ] + }, + "ListAwsNodePools": { + "methods": [ + "list_aws_node_pools" + ] + }, + "RollbackAwsNodePoolUpdate": { + "methods": [ + "rollback_aws_node_pool_update" + ] + }, + "UpdateAwsCluster": { + "methods": [ + "update_aws_cluster" + ] + }, + "UpdateAwsNodePool": { + "methods": [ + "update_aws_node_pool" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AwsClustersAsyncClient", + "rpcs": { + "CreateAwsCluster": { + "methods": [ + "create_aws_cluster" + ] + }, + "CreateAwsNodePool": { + "methods": [ + "create_aws_node_pool" + ] + }, + "DeleteAwsCluster": { + "methods": [ + "delete_aws_cluster" + ] + }, + "DeleteAwsNodePool": { + "methods": [ + "delete_aws_node_pool" + ] + }, + "GenerateAwsAccessToken": { + "methods": [ + "generate_aws_access_token" + ] + }, + "GenerateAwsClusterAgentToken": { + "methods": [ + "generate_aws_cluster_agent_token" + ] + }, + "GetAwsCluster": { + "methods": [ + "get_aws_cluster" + ] + }, + "GetAwsJsonWebKeys": { + "methods": [ + "get_aws_json_web_keys" + ] + }, + "GetAwsNodePool": { + "methods": [ + "get_aws_node_pool" + ] + }, + "GetAwsOpenIdConfig": { + "methods": [ + "get_aws_open_id_config" + ] + }, + "GetAwsServerConfig": { + "methods": [ + "get_aws_server_config" + ] + }, + "ListAwsClusters": { + "methods": [ + "list_aws_clusters" + ] + }, + "ListAwsNodePools": { + "methods": [ + "list_aws_node_pools" + ] + }, + "RollbackAwsNodePoolUpdate": { + "methods": [ + "rollback_aws_node_pool_update" + ] + }, + "UpdateAwsCluster": { + "methods": [ + "update_aws_cluster" + ] + }, + "UpdateAwsNodePool": { + "methods": [ + "update_aws_node_pool" + ] + } + } + }, + "rest": { + "libraryClient": "AwsClustersClient", + "rpcs": { + "CreateAwsCluster": { + "methods": [ + "create_aws_cluster" + ] + }, + "CreateAwsNodePool": { + "methods": [ + "create_aws_node_pool" + ] + }, + "DeleteAwsCluster": { + "methods": [ + "delete_aws_cluster" + ] + }, + "DeleteAwsNodePool": { + "methods": [ + "delete_aws_node_pool" + ] + }, + "GenerateAwsAccessToken": { + "methods": [ + "generate_aws_access_token" + ] + }, + "GenerateAwsClusterAgentToken": { + "methods": [ + "generate_aws_cluster_agent_token" + ] + }, + "GetAwsCluster": { + "methods": [ + "get_aws_cluster" + ] + }, + "GetAwsJsonWebKeys": { + "methods": [ + "get_aws_json_web_keys" + ] + }, + "GetAwsNodePool": { + "methods": [ + "get_aws_node_pool" + ] + }, + "GetAwsOpenIdConfig": { + "methods": [ + "get_aws_open_id_config" + ] + }, + "GetAwsServerConfig": { + "methods": [ + "get_aws_server_config" + ] + }, + "ListAwsClusters": { + "methods": [ + "list_aws_clusters" + ] + }, + "ListAwsNodePools": { + "methods": [ + "list_aws_node_pools" + ] + }, + "RollbackAwsNodePoolUpdate": { + "methods": [ + "rollback_aws_node_pool_update" + ] + }, + "UpdateAwsCluster": { + "methods": [ + "update_aws_cluster" + ] + }, + "UpdateAwsNodePool": { + "methods": [ + "update_aws_node_pool" + ] + } + } + } + } + }, + "AzureClusters": { + "clients": { + "grpc": { + "libraryClient": "AzureClustersClient", + "rpcs": { + "CreateAzureClient": { + "methods": [ + "create_azure_client" + ] + }, + "CreateAzureCluster": { + "methods": [ + "create_azure_cluster" + ] + }, + "CreateAzureNodePool": { + "methods": [ + "create_azure_node_pool" + ] + }, + "DeleteAzureClient": { + "methods": [ + "delete_azure_client" + ] + }, + "DeleteAzureCluster": { + "methods": [ + "delete_azure_cluster" + ] + }, + "DeleteAzureNodePool": { + "methods": [ + "delete_azure_node_pool" + ] + }, + "GenerateAzureAccessToken": { + "methods": [ + "generate_azure_access_token" + ] + }, + "GenerateAzureClusterAgentToken": { + "methods": [ + "generate_azure_cluster_agent_token" + ] + }, + "GetAzureClient": { + "methods": [ + "get_azure_client" + ] + }, + "GetAzureCluster": { + "methods": [ + "get_azure_cluster" + ] + }, + "GetAzureJsonWebKeys": { + "methods": [ + "get_azure_json_web_keys" + ] + }, + "GetAzureNodePool": { + "methods": [ + "get_azure_node_pool" + ] + }, + "GetAzureOpenIdConfig": { + "methods": [ + "get_azure_open_id_config" + ] + }, + "GetAzureServerConfig": { + "methods": [ + "get_azure_server_config" + ] + }, + "ListAzureClients": { + "methods": [ + "list_azure_clients" + ] + }, + "ListAzureClusters": { + "methods": [ + "list_azure_clusters" + ] + }, + "ListAzureNodePools": { + "methods": [ + "list_azure_node_pools" + ] + }, + "UpdateAzureCluster": { + "methods": [ + "update_azure_cluster" + ] + }, + "UpdateAzureNodePool": { + "methods": [ + "update_azure_node_pool" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AzureClustersAsyncClient", + "rpcs": { + "CreateAzureClient": { + "methods": [ + "create_azure_client" + ] + }, + "CreateAzureCluster": { + "methods": [ + "create_azure_cluster" + ] + }, + "CreateAzureNodePool": { + "methods": [ + "create_azure_node_pool" + ] + }, + "DeleteAzureClient": { + "methods": [ + "delete_azure_client" + ] + }, + "DeleteAzureCluster": { + "methods": [ + "delete_azure_cluster" + ] + }, + "DeleteAzureNodePool": { + "methods": [ + "delete_azure_node_pool" + ] + }, + "GenerateAzureAccessToken": { + "methods": [ + "generate_azure_access_token" + ] + }, + "GenerateAzureClusterAgentToken": { + "methods": [ + "generate_azure_cluster_agent_token" + ] + }, + "GetAzureClient": { + "methods": [ + "get_azure_client" + ] + }, + "GetAzureCluster": { + "methods": [ + "get_azure_cluster" + ] + }, + "GetAzureJsonWebKeys": { + "methods": [ + "get_azure_json_web_keys" + ] + }, + "GetAzureNodePool": { + "methods": [ + "get_azure_node_pool" + ] + }, + "GetAzureOpenIdConfig": { + "methods": [ + "get_azure_open_id_config" + ] + }, + "GetAzureServerConfig": { + "methods": [ + "get_azure_server_config" + ] + }, + "ListAzureClients": { + "methods": [ + "list_azure_clients" + ] + }, + "ListAzureClusters": { + "methods": [ + "list_azure_clusters" + ] + }, + "ListAzureNodePools": { + "methods": [ + "list_azure_node_pools" + ] + }, + "UpdateAzureCluster": { + "methods": [ + "update_azure_cluster" + ] + }, + "UpdateAzureNodePool": { + "methods": [ + "update_azure_node_pool" + ] + } + } + }, + "rest": { + "libraryClient": "AzureClustersClient", + "rpcs": { + "CreateAzureClient": { + "methods": [ + "create_azure_client" + ] + }, + "CreateAzureCluster": { + "methods": [ + "create_azure_cluster" + ] + }, + "CreateAzureNodePool": { + "methods": [ + "create_azure_node_pool" + ] + }, + "DeleteAzureClient": { + "methods": [ + "delete_azure_client" + ] + }, + "DeleteAzureCluster": { + "methods": [ + "delete_azure_cluster" + ] + }, + "DeleteAzureNodePool": { + "methods": [ + "delete_azure_node_pool" + ] + }, + "GenerateAzureAccessToken": { + "methods": [ + "generate_azure_access_token" + ] + }, + "GenerateAzureClusterAgentToken": { + "methods": [ + "generate_azure_cluster_agent_token" + ] + }, + "GetAzureClient": { + "methods": [ + "get_azure_client" + ] + }, + "GetAzureCluster": { + "methods": [ + "get_azure_cluster" + ] + }, + "GetAzureJsonWebKeys": { + "methods": [ + "get_azure_json_web_keys" + ] + }, + "GetAzureNodePool": { + "methods": [ + "get_azure_node_pool" + ] + }, + "GetAzureOpenIdConfig": { + "methods": [ + "get_azure_open_id_config" + ] + }, + "GetAzureServerConfig": { + "methods": [ + "get_azure_server_config" + ] + }, + "ListAzureClients": { + "methods": [ + "list_azure_clients" + ] + }, + "ListAzureClusters": { + "methods": [ + "list_azure_clusters" + ] + }, + "ListAzureNodePools": { + "methods": [ + "list_azure_node_pools" + ] + }, + "UpdateAzureCluster": { + "methods": [ + "update_azure_cluster" + ] + }, + "UpdateAzureNodePool": { + "methods": [ + "update_azure_node_pool" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_version.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/py.typed b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/py.typed new file mode 100644 index 000000000000..53546ad8d1e7 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gke-multicloud package uses inline types. diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/__init__.py new file mode 100644 index 000000000000..70436f571973 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AttachedClustersClient +from .async_client import AttachedClustersAsyncClient + +__all__ = ( + 'AttachedClustersClient', + 'AttachedClustersAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/async_client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/async_client.py new file mode 100644 index 000000000000..79bf63e6cc67 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/async_client.py @@ -0,0 +1,1691 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.gke_multicloud_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.gke_multicloud_v1.services.attached_clusters import pagers +from google.cloud.gke_multicloud_v1.types import attached_resources +from google.cloud.gke_multicloud_v1.types import attached_service +from google.cloud.gke_multicloud_v1.types import common_resources +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AttachedClustersTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AttachedClustersGrpcAsyncIOTransport +from .client import AttachedClustersClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class AttachedClustersAsyncClient: + """The AttachedClusters API provides a single centrally managed + service to register and manage Anthos attached clusters that run + on customer's owned infrastructure. + """ + + _client: AttachedClustersClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AttachedClustersClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AttachedClustersClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AttachedClustersClient._DEFAULT_UNIVERSE + + attached_cluster_path = staticmethod(AttachedClustersClient.attached_cluster_path) + parse_attached_cluster_path = staticmethod(AttachedClustersClient.parse_attached_cluster_path) + attached_server_config_path = staticmethod(AttachedClustersClient.attached_server_config_path) + parse_attached_server_config_path = staticmethod(AttachedClustersClient.parse_attached_server_config_path) + common_billing_account_path = staticmethod(AttachedClustersClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AttachedClustersClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AttachedClustersClient.common_folder_path) + parse_common_folder_path = staticmethod(AttachedClustersClient.parse_common_folder_path) + common_organization_path = staticmethod(AttachedClustersClient.common_organization_path) + parse_common_organization_path = staticmethod(AttachedClustersClient.parse_common_organization_path) + common_project_path = staticmethod(AttachedClustersClient.common_project_path) + parse_common_project_path = staticmethod(AttachedClustersClient.parse_common_project_path) + common_location_path = staticmethod(AttachedClustersClient.common_location_path) + parse_common_location_path = staticmethod(AttachedClustersClient.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: + AttachedClustersAsyncClient: The constructed client. + """ + return AttachedClustersClient.from_service_account_info.__func__(AttachedClustersAsyncClient, 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: + AttachedClustersAsyncClient: The constructed client. + """ + return AttachedClustersClient.from_service_account_file.__func__(AttachedClustersAsyncClient, 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 AttachedClustersClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AttachedClustersTransport: + """Returns the transport used by the client instance. + + Returns: + AttachedClustersTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = AttachedClustersClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AttachedClustersTransport, Callable[..., AttachedClustersTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the attached clusters async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AttachedClustersTransport,Callable[..., AttachedClustersTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AttachedClustersTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AttachedClustersClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.gkemulticloud_v1.AttachedClustersAsyncClient`.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "credentialsType": None, + } + ) + + async def create_attached_cluster(self, + request: Optional[Union[attached_service.CreateAttachedClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + attached_cluster: Optional[attached_resources.AttachedCluster] = None, + attached_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_create_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + attached_cluster = gke_multicloud_v1.AttachedCluster() + attached_cluster.platform_version = "platform_version_value" + attached_cluster.distribution = "distribution_value" + attached_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAttachedClusterRequest( + parent="parent_value", + attached_cluster=attached_cluster, + attached_cluster_id="attached_cluster_id_value", + ) + + # Make the request + operation = client.create_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAttachedClusterRequest, dict]]): + The request object. Request message for + ``AttachedClusters.CreateAttachedCluster`` method. + parent (:class:`str`): + Required. The parent location where this + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + attached_cluster (:class:`google.cloud.gke_multicloud_v1.types.AttachedCluster`): + Required. The specification of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + to create. + + This corresponds to the ``attached_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + attached_cluster_id (:class:`str`): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource name formatted as + ``projects//locations//attachedClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``attached_cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AttachedCluster` + An Anthos cluster running on customer own + infrastructure. + + """ + # 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, attached_cluster, attached_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.CreateAttachedClusterRequest): + request = attached_service.CreateAttachedClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if attached_cluster is not None: + request.attached_cluster = attached_cluster + if attached_cluster_id is not None: + request.attached_cluster_id = attached_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_attached_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + attached_resources.AttachedCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_attached_cluster(self, + request: Optional[Union[attached_service.UpdateAttachedClusterRequest, dict]] = None, + *, + attached_cluster: Optional[attached_resources.AttachedCluster] = 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, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. + + .. 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 gke_multicloud_v1 + + async def sample_update_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + attached_cluster = gke_multicloud_v1.AttachedCluster() + attached_cluster.platform_version = "platform_version_value" + attached_cluster.distribution = "distribution_value" + attached_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAttachedClusterRequest( + attached_cluster=attached_cluster, + ) + + # Make the request + operation = client.update_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.UpdateAttachedClusterRequest, dict]]): + The request object. Request message for + ``AttachedClusters.UpdateAttachedCluster`` method. + attached_cluster (:class:`google.cloud.gke_multicloud_v1.types.AttachedCluster`): + Required. The + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource to update. + + This corresponds to the ``attached_cluster`` 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 path + must be supplied in this field. The elements of the + repeated paths field can only include these fields from + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]: + + - ``annotations``. + - ``authorization.admin_groups``. + - ``authorization.admin_users``. + - ``binary_authorization.evaluation_mode``. + - ``description``. + - ``logging_config.component_config.enable_components``. + - ``monitoring_config.managed_prometheus_config.enabled``. + - ``platform_version``. + - ``proxy_config.kubernetes_secret.name``. + - ``proxy_config.kubernetes_secret.namespace``. + - ``security_posture_config.vulnerability_mode`` + - ``monitoring_config.cloud_monitoring_config.enabled`` + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AttachedCluster` + An Anthos cluster running on customer own + infrastructure. + + """ + # 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([attached_cluster, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.UpdateAttachedClusterRequest): + request = attached_service.UpdateAttachedClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attached_cluster is not None: + request.attached_cluster = attached_cluster + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_attached_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attached_cluster.name", request.attached_cluster.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + attached_resources.AttachedCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def import_attached_cluster(self, + request: Optional[Union[attached_service.ImportAttachedClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + fleet_membership: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports creates a new + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource by importing an existing Fleet Membership resource. + + Attached Clusters created before the introduction of the Anthos + Multi-Cloud API can be imported through this method. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_import_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ImportAttachedClusterRequest( + parent="parent_value", + fleet_membership="fleet_membership_value", + platform_version="platform_version_value", + distribution="distribution_value", + ) + + # Make the request + operation = client.import_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.ImportAttachedClusterRequest, dict]]): + The request object. Request message for + ``AttachedClusters.ImportAttachedCluster`` method. + parent (:class:`str`): + Required. The parent location where this + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + fleet_membership (:class:`str`): + Required. The name of the fleet + membership resource to import. + + This corresponds to the ``fleet_membership`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AttachedCluster` + An Anthos cluster running on customer own + infrastructure. + + """ + # 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, fleet_membership]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.ImportAttachedClusterRequest): + request = attached_service.ImportAttachedClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if fleet_membership is not None: + request.fleet_membership = fleet_membership + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.import_attached_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + attached_resources.AttachedCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_attached_cluster(self, + request: Optional[Union[attached_service.GetAttachedClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> attached_resources.AttachedCluster: + r"""Describes a specific + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + 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 gke_multicloud_v1 + + async def sample_get_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAttachedClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attached_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAttachedClusterRequest, dict]]): + The request object. Request message for + ``AttachedClusters.GetAttachedCluster`` method. + name (:class:`str`): + Required. The name of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource to describe. + + ``AttachedCluster`` names are formatted as + ``projects//locations//attachedClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AttachedCluster: + An Anthos cluster running on customer + own infrastructure. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.GetAttachedClusterRequest): + request = attached_service.GetAttachedClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_attached_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_attached_clusters(self, + request: Optional[Union[attached_service.ListAttachedClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAttachedClustersAsyncPager: + r"""Lists all + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resources on a given Google Cloud project and region. + + .. 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 gke_multicloud_v1 + + async def sample_list_attached_clusters(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAttachedClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attached_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest, dict]]): + The request object. Request message for + ``AttachedClusters.ListAttachedClusters`` method. + parent (:class:`str`): + Required. The parent location which owns this collection + of + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.attached_clusters.pagers.ListAttachedClustersAsyncPager: + Response message for + AttachedClusters.ListAttachedClusters method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.ListAttachedClustersRequest): + request = attached_service.ListAttachedClustersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_attached_clusters] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAttachedClustersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_attached_cluster(self, + request: Optional[Union[attached_service.DeleteAttachedClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a specific + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_delete_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAttachedClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAttachedClusterRequest, dict]]): + The request object. Request message for + ``AttachedClusters.DeleteAttachedCluster`` method. + name (:class:`str`): + Required. The resource name the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + to delete. + + ``AttachedCluster`` names are formatted as + ``projects//locations//attachedClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.DeleteAttachedClusterRequest): + request = attached_service.DeleteAttachedClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_attached_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_attached_server_config(self, + request: Optional[Union[attached_service.GetAttachedServerConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> attached_resources.AttachedServerConfig: + r"""Returns information, such as supported Kubernetes + versions, on a given Google Cloud 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 gke_multicloud_v1 + + async def sample_get_attached_server_config(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAttachedServerConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attached_server_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAttachedServerConfigRequest, dict]]): + The request object. GetAttachedServerConfigRequest gets + the server config for attached clusters. + name (:class:`str`): + Required. The name of the + [AttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedServerConfig] + resource to describe. + + ``AttachedServerConfig`` names are formatted as + ``projects//locations//attachedServerConfig``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AttachedServerConfig: + AttachedServerConfig provides + information about supported Kubernetes + versions + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.GetAttachedServerConfigRequest): + request = attached_service.GetAttachedServerConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_attached_server_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_attached_cluster_install_manifest(self, + request: Optional[Union[attached_service.GenerateAttachedClusterInstallManifestRequest, dict]] = None, + *, + parent: Optional[str] = None, + attached_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> attached_service.GenerateAttachedClusterInstallManifestResponse: + r"""Generates the install manifest to be installed on the + target 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 gke_multicloud_v1 + + async def sample_generate_attached_cluster_install_manifest(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAttachedClusterInstallManifestRequest( + parent="parent_value", + attached_cluster_id="attached_cluster_id_value", + platform_version="platform_version_value", + ) + + # Make the request + response = await client.generate_attached_cluster_install_manifest(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestRequest, dict]]): + The request object. Request message for + ``AttachedClusters.GenerateAttachedClusterInstallManifest`` + method. + parent (:class:`str`): + Required. The parent location where this + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + attached_cluster_id (:class:`str`): + Required. A client provided ID of the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource name formatted as + ``projects//locations//attachedClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + When generating an install manifest for importing an + existing Membership resource, the attached_cluster_id + field must be the Membership id. + + Membership names are formatted as + ``projects//locations//memberships/``. + + This corresponds to the ``attached_cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestResponse: + Response message for + AttachedClusters.GenerateAttachedClusterInstallManifest + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, attached_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.GenerateAttachedClusterInstallManifestRequest): + request = attached_service.GenerateAttachedClusterInstallManifestRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if attached_cluster_id is not None: + request.attached_cluster_id = attached_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_attached_cluster_install_manifest] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_attached_cluster_agent_token(self, + request: Optional[Union[attached_service.GenerateAttachedClusterAgentTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> attached_service.GenerateAttachedClusterAgentTokenResponse: + r"""Generates an access token for a cluster agent. + + .. 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 gke_multicloud_v1 + + async def sample_generate_attached_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAttachedClusterAgentTokenRequest( + attached_cluster="attached_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = await client.generate_attached_cluster_agent_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenRequest, dict]]): + The request object. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenResponse: + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.GenerateAttachedClusterAgentTokenRequest): + request = attached_service.GenerateAttachedClusterAgentTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_attached_cluster_agent_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attached_cluster", request.attached_cluster), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def 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, Union[str, bytes]]] = (), + ) -> 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + 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, Union[str, bytes]]] = (), + ) -> 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "AttachedClustersAsyncClient": + 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__ = ( + "AttachedClustersAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/client.py new file mode 100644 index 000000000000..90e2468d03a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/client.py @@ -0,0 +1,2028 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.gke_multicloud_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.gke_multicloud_v1.services.attached_clusters import pagers +from google.cloud.gke_multicloud_v1.types import attached_resources +from google.cloud.gke_multicloud_v1.types import attached_service +from google.cloud.gke_multicloud_v1.types import common_resources +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AttachedClustersTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AttachedClustersGrpcTransport +from .transports.grpc_asyncio import AttachedClustersGrpcAsyncIOTransport +from .transports.rest import AttachedClustersRestTransport + + +class AttachedClustersClientMeta(type): + """Metaclass for the AttachedClusters 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[AttachedClustersTransport]] + _transport_registry["grpc"] = AttachedClustersGrpcTransport + _transport_registry["grpc_asyncio"] = AttachedClustersGrpcAsyncIOTransport + _transport_registry["rest"] = AttachedClustersRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AttachedClustersTransport]: + """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 AttachedClustersClient(metaclass=AttachedClustersClientMeta): + """The AttachedClusters API provides a single centrally managed + service to register and manage Anthos attached clusters that run + on customer's owned infrastructure. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "gkemulticloud.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "gkemulticloud.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AttachedClustersClient: 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: + AttachedClustersClient: 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) -> AttachedClustersTransport: + """Returns the transport used by the client instance. + + Returns: + AttachedClustersTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attached_cluster_path(project: str,location: str,attached_cluster: str,) -> str: + """Returns a fully-qualified attached_cluster string.""" + return "projects/{project}/locations/{location}/attachedClusters/{attached_cluster}".format(project=project, location=location, attached_cluster=attached_cluster, ) + + @staticmethod + def parse_attached_cluster_path(path: str) -> Dict[str,str]: + """Parses a attached_cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/attachedClusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def attached_server_config_path(project: str,location: str,) -> str: + """Returns a fully-qualified attached_server_config string.""" + return "projects/{project}/locations/{location}/attachedServerConfig".format(project=project, location=location, ) + + @staticmethod + def parse_attached_server_config_path(path: str) -> Dict[str,str]: + """Parses a attached_server_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/attachedServerConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = AttachedClustersClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AttachedClustersClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AttachedClustersClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AttachedClustersTransport, Callable[..., AttachedClustersTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the attached clusters client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AttachedClustersTransport,Callable[..., AttachedClustersTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AttachedClustersTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AttachedClustersClient._read_environment_variables() + self._client_cert_source = AttachedClustersClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AttachedClustersClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AttachedClustersTransport) + if transport_provided: + # transport is a AttachedClustersTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(AttachedClustersTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AttachedClustersClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[AttachedClustersTransport], Callable[..., AttachedClustersTransport]] = ( + AttachedClustersClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AttachedClustersTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.gkemulticloud_v1.AttachedClustersClient`.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "credentialsType": None, + } + ) + + def create_attached_cluster(self, + request: Optional[Union[attached_service.CreateAttachedClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + attached_cluster: Optional[attached_resources.AttachedCluster] = None, + attached_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_create_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + attached_cluster = gke_multicloud_v1.AttachedCluster() + attached_cluster.platform_version = "platform_version_value" + attached_cluster.distribution = "distribution_value" + attached_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAttachedClusterRequest( + parent="parent_value", + attached_cluster=attached_cluster, + attached_cluster_id="attached_cluster_id_value", + ) + + # Make the request + operation = client.create_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.CreateAttachedClusterRequest, dict]): + The request object. Request message for + ``AttachedClusters.CreateAttachedCluster`` method. + parent (str): + Required. The parent location where this + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + attached_cluster (google.cloud.gke_multicloud_v1.types.AttachedCluster): + Required. The specification of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + to create. + + This corresponds to the ``attached_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + attached_cluster_id (str): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource name formatted as + ``projects//locations//attachedClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``attached_cluster_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AttachedCluster` + An Anthos cluster running on customer own + infrastructure. + + """ + # 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, attached_cluster, attached_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.CreateAttachedClusterRequest): + request = attached_service.CreateAttachedClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if attached_cluster is not None: + request.attached_cluster = attached_cluster + if attached_cluster_id is not None: + request.attached_cluster_id = attached_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_attached_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + attached_resources.AttachedCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_attached_cluster(self, + request: Optional[Union[attached_service.UpdateAttachedClusterRequest, dict]] = None, + *, + attached_cluster: Optional[attached_resources.AttachedCluster] = 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, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates an + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. + + .. 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 gke_multicloud_v1 + + def sample_update_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + attached_cluster = gke_multicloud_v1.AttachedCluster() + attached_cluster.platform_version = "platform_version_value" + attached_cluster.distribution = "distribution_value" + attached_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAttachedClusterRequest( + attached_cluster=attached_cluster, + ) + + # Make the request + operation = client.update_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.UpdateAttachedClusterRequest, dict]): + The request object. Request message for + ``AttachedClusters.UpdateAttachedCluster`` method. + attached_cluster (google.cloud.gke_multicloud_v1.types.AttachedCluster): + Required. The + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource to update. + + This corresponds to the ``attached_cluster`` 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 path + must be supplied in this field. The elements of the + repeated paths field can only include these fields from + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]: + + - ``annotations``. + - ``authorization.admin_groups``. + - ``authorization.admin_users``. + - ``binary_authorization.evaluation_mode``. + - ``description``. + - ``logging_config.component_config.enable_components``. + - ``monitoring_config.managed_prometheus_config.enabled``. + - ``platform_version``. + - ``proxy_config.kubernetes_secret.name``. + - ``proxy_config.kubernetes_secret.namespace``. + - ``security_posture_config.vulnerability_mode`` + - ``monitoring_config.cloud_monitoring_config.enabled`` + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AttachedCluster` + An Anthos cluster running on customer own + infrastructure. + + """ + # 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([attached_cluster, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.UpdateAttachedClusterRequest): + request = attached_service.UpdateAttachedClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attached_cluster is not None: + request.attached_cluster = attached_cluster + 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_attached_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attached_cluster.name", request.attached_cluster.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + attached_resources.AttachedCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def import_attached_cluster(self, + request: Optional[Union[attached_service.ImportAttachedClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + fleet_membership: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Imports creates a new + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource by importing an existing Fleet Membership resource. + + Attached Clusters created before the introduction of the Anthos + Multi-Cloud API can be imported through this method. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_import_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ImportAttachedClusterRequest( + parent="parent_value", + fleet_membership="fleet_membership_value", + platform_version="platform_version_value", + distribution="distribution_value", + ) + + # Make the request + operation = client.import_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.ImportAttachedClusterRequest, dict]): + The request object. Request message for + ``AttachedClusters.ImportAttachedCluster`` method. + parent (str): + Required. The parent location where this + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + fleet_membership (str): + Required. The name of the fleet + membership resource to import. + + This corresponds to the ``fleet_membership`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AttachedCluster` + An Anthos cluster running on customer own + infrastructure. + + """ + # 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, fleet_membership]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.ImportAttachedClusterRequest): + request = attached_service.ImportAttachedClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if fleet_membership is not None: + request.fleet_membership = fleet_membership + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_attached_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + attached_resources.AttachedCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_attached_cluster(self, + request: Optional[Union[attached_service.GetAttachedClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> attached_resources.AttachedCluster: + r"""Describes a specific + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + 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 gke_multicloud_v1 + + def sample_get_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAttachedClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_attached_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAttachedClusterRequest, dict]): + The request object. Request message for + ``AttachedClusters.GetAttachedCluster`` method. + name (str): + Required. The name of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource to describe. + + ``AttachedCluster`` names are formatted as + ``projects//locations//attachedClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AttachedCluster: + An Anthos cluster running on customer + own infrastructure. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.GetAttachedClusterRequest): + request = attached_service.GetAttachedClusterRequest(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_attached_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_attached_clusters(self, + request: Optional[Union[attached_service.ListAttachedClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAttachedClustersPager: + r"""Lists all + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resources on a given Google Cloud project and region. + + .. 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 gke_multicloud_v1 + + def sample_list_attached_clusters(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAttachedClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attached_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest, dict]): + The request object. Request message for + ``AttachedClusters.ListAttachedClusters`` method. + parent (str): + Required. The parent location which owns this collection + of + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.attached_clusters.pagers.ListAttachedClustersPager: + Response message for + AttachedClusters.ListAttachedClusters method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.ListAttachedClustersRequest): + request = attached_service.ListAttachedClustersRequest(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_attached_clusters] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAttachedClustersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_attached_cluster(self, + request: Optional[Union[attached_service.DeleteAttachedClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a specific + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_delete_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAttachedClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.DeleteAttachedClusterRequest, dict]): + The request object. Request message for + ``AttachedClusters.DeleteAttachedCluster`` method. + name (str): + Required. The resource name the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + to delete. + + ``AttachedCluster`` names are formatted as + ``projects//locations//attachedClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.DeleteAttachedClusterRequest): + request = attached_service.DeleteAttachedClusterRequest(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_attached_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_attached_server_config(self, + request: Optional[Union[attached_service.GetAttachedServerConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> attached_resources.AttachedServerConfig: + r"""Returns information, such as supported Kubernetes + versions, on a given Google Cloud 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 gke_multicloud_v1 + + def sample_get_attached_server_config(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAttachedServerConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attached_server_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAttachedServerConfigRequest, dict]): + The request object. GetAttachedServerConfigRequest gets + the server config for attached clusters. + name (str): + Required. The name of the + [AttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedServerConfig] + resource to describe. + + ``AttachedServerConfig`` names are formatted as + ``projects//locations//attachedServerConfig``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AttachedServerConfig: + AttachedServerConfig provides + information about supported Kubernetes + versions + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.GetAttachedServerConfigRequest): + request = attached_service.GetAttachedServerConfigRequest(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_attached_server_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_attached_cluster_install_manifest(self, + request: Optional[Union[attached_service.GenerateAttachedClusterInstallManifestRequest, dict]] = None, + *, + parent: Optional[str] = None, + attached_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> attached_service.GenerateAttachedClusterInstallManifestResponse: + r"""Generates the install manifest to be installed on the + target 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 gke_multicloud_v1 + + def sample_generate_attached_cluster_install_manifest(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAttachedClusterInstallManifestRequest( + parent="parent_value", + attached_cluster_id="attached_cluster_id_value", + platform_version="platform_version_value", + ) + + # Make the request + response = client.generate_attached_cluster_install_manifest(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestRequest, dict]): + The request object. Request message for + ``AttachedClusters.GenerateAttachedClusterInstallManifest`` + method. + parent (str): + Required. The parent location where this + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + attached_cluster_id (str): + Required. A client provided ID of the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource name formatted as + ``projects//locations//attachedClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + When generating an install manifest for importing an + existing Membership resource, the attached_cluster_id + field must be the Membership id. + + Membership names are formatted as + ``projects//locations//memberships/``. + + This corresponds to the ``attached_cluster_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestResponse: + Response message for + AttachedClusters.GenerateAttachedClusterInstallManifest + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, attached_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.GenerateAttachedClusterInstallManifestRequest): + request = attached_service.GenerateAttachedClusterInstallManifestRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if attached_cluster_id is not None: + request.attached_cluster_id = attached_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_attached_cluster_install_manifest] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_attached_cluster_agent_token(self, + request: Optional[Union[attached_service.GenerateAttachedClusterAgentTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> attached_service.GenerateAttachedClusterAgentTokenResponse: + r"""Generates an access token for a cluster agent. + + .. 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 gke_multicloud_v1 + + def sample_generate_attached_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAttachedClusterAgentTokenRequest( + attached_cluster="attached_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = client.generate_attached_cluster_agent_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenRequest, dict]): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenResponse: + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, attached_service.GenerateAttachedClusterAgentTokenRequest): + request = attached_service.GenerateAttachedClusterAgentTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_attached_cluster_agent_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attached_cluster", request.attached_cluster), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AttachedClustersClient": + 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, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def 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, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + 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, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AttachedClustersClient", +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/pagers.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/pagers.py new file mode 100644 index 000000000000..7c9b1f9cba56 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/pagers.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.gke_multicloud_v1.types import attached_resources +from google.cloud.gke_multicloud_v1.types import attached_service + + +class ListAttachedClustersPager: + """A pager for iterating through ``list_attached_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``attached_clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAttachedClusters`` requests and continue to iterate + through the ``attached_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse` + 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[..., attached_service.ListAttachedClustersResponse], + request: attached_service.ListAttachedClustersRequest, + response: attached_service.ListAttachedClustersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = attached_service.ListAttachedClustersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[attached_service.ListAttachedClustersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[attached_resources.AttachedCluster]: + for page in self.pages: + yield from page.attached_clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAttachedClustersAsyncPager: + """A pager for iterating through ``list_attached_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``attached_clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAttachedClusters`` requests and continue to iterate + through the ``attached_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse` + 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[attached_service.ListAttachedClustersResponse]], + request: attached_service.ListAttachedClustersRequest, + response: attached_service.ListAttachedClustersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = attached_service.ListAttachedClustersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[attached_service.ListAttachedClustersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[attached_resources.AttachedCluster]: + async def async_generator(): + async for page in self.pages: + for response in page.attached_clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/README.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/README.rst new file mode 100644 index 000000000000..6dc5686bab67 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AttachedClustersTransport` is the ABC for all transports. +- public child `AttachedClustersGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AttachedClustersGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAttachedClustersRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AttachedClustersRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/__init__.py new file mode 100644 index 000000000000..73db2bf098c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AttachedClustersTransport +from .grpc import AttachedClustersGrpcTransport +from .grpc_asyncio import AttachedClustersGrpcAsyncIOTransport +from .rest import AttachedClustersRestTransport +from .rest import AttachedClustersRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AttachedClustersTransport]] +_transport_registry['grpc'] = AttachedClustersGrpcTransport +_transport_registry['grpc_asyncio'] = AttachedClustersGrpcAsyncIOTransport +_transport_registry['rest'] = AttachedClustersRestTransport + +__all__ = ( + 'AttachedClustersTransport', + 'AttachedClustersGrpcTransport', + 'AttachedClustersGrpcAsyncIOTransport', + 'AttachedClustersRestTransport', + 'AttachedClustersRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/base.py new file mode 100644 index 000000000000..55700e7ce90a --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/base.py @@ -0,0 +1,375 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.gke_multicloud_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.gke_multicloud_v1.types import attached_resources +from google.cloud.gke_multicloud_v1.types import attached_service +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AttachedClustersTransport(abc.ABC): + """Abstract transport class for AttachedClusters.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'gkemulticloud.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_attached_cluster: gapic_v1.method.wrap_method( + self.create_attached_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_attached_cluster: gapic_v1.method.wrap_method( + self.update_attached_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.import_attached_cluster: gapic_v1.method.wrap_method( + self.import_attached_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_attached_cluster: gapic_v1.method.wrap_method( + self.get_attached_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_attached_clusters: gapic_v1.method.wrap_method( + self.list_attached_clusters, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_attached_cluster: gapic_v1.method.wrap_method( + self.delete_attached_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_attached_server_config: gapic_v1.method.wrap_method( + self.get_attached_server_config, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_attached_cluster_install_manifest: gapic_v1.method.wrap_method( + self.generate_attached_cluster_install_manifest, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_attached_cluster_agent_token: gapic_v1.method.wrap_method( + self.generate_attached_cluster_agent_token, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + 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 create_attached_cluster(self) -> Callable[ + [attached_service.CreateAttachedClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_attached_cluster(self) -> Callable[ + [attached_service.UpdateAttachedClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_attached_cluster(self) -> Callable[ + [attached_service.ImportAttachedClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_attached_cluster(self) -> Callable[ + [attached_service.GetAttachedClusterRequest], + Union[ + attached_resources.AttachedCluster, + Awaitable[attached_resources.AttachedCluster] + ]]: + raise NotImplementedError() + + @property + def list_attached_clusters(self) -> Callable[ + [attached_service.ListAttachedClustersRequest], + Union[ + attached_service.ListAttachedClustersResponse, + Awaitable[attached_service.ListAttachedClustersResponse] + ]]: + raise NotImplementedError() + + @property + def delete_attached_cluster(self) -> Callable[ + [attached_service.DeleteAttachedClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_attached_server_config(self) -> Callable[ + [attached_service.GetAttachedServerConfigRequest], + Union[ + attached_resources.AttachedServerConfig, + Awaitable[attached_resources.AttachedServerConfig] + ]]: + raise NotImplementedError() + + @property + def generate_attached_cluster_install_manifest(self) -> Callable[ + [attached_service.GenerateAttachedClusterInstallManifestRequest], + Union[ + attached_service.GenerateAttachedClusterInstallManifestResponse, + Awaitable[attached_service.GenerateAttachedClusterInstallManifestResponse] + ]]: + raise NotImplementedError() + + @property + def generate_attached_cluster_agent_token(self) -> Callable[ + [attached_service.GenerateAttachedClusterAgentTokenRequest], + Union[ + attached_service.GenerateAttachedClusterAgentTokenResponse, + Awaitable[attached_service.GenerateAttachedClusterAgentTokenResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AttachedClustersTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc.py new file mode 100644 index 000000000000..ee820d99e000 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc.py @@ -0,0 +1,679 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +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 +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.gke_multicloud_v1.types import attached_resources +from google.cloud.gke_multicloud_v1.types import attached_service +from google.longrunning import operations_pb2 # type: ignore +from .base import AttachedClustersTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AttachedClustersGrpcTransport(AttachedClustersTransport): + """gRPC backend transport for AttachedClusters. + + The AttachedClusters API provides a single centrally managed + service to register and manage Anthos attached clusters that run + on customer's owned infrastructure. + + 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 = 'gkemulticloud.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'gkemulticloud.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._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_attached_cluster(self) -> Callable[ + [attached_service.CreateAttachedClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create attached cluster method over gRPC. + + Creates a new + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAttachedClusterRequest], + ~.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_attached_cluster' not in self._stubs: + self._stubs['create_attached_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/CreateAttachedCluster', + request_serializer=attached_service.CreateAttachedClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_attached_cluster'] + + @property + def update_attached_cluster(self) -> Callable[ + [attached_service.UpdateAttachedClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update attached cluster method over gRPC. + + Updates an + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. + + Returns: + Callable[[~.UpdateAttachedClusterRequest], + ~.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_attached_cluster' not in self._stubs: + self._stubs['update_attached_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/UpdateAttachedCluster', + request_serializer=attached_service.UpdateAttachedClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_attached_cluster'] + + @property + def import_attached_cluster(self) -> Callable[ + [attached_service.ImportAttachedClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the import attached cluster method over gRPC. + + Imports creates a new + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource by importing an existing Fleet Membership resource. + + Attached Clusters created before the introduction of the Anthos + Multi-Cloud API can be imported through this method. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.ImportAttachedClusterRequest], + ~.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 'import_attached_cluster' not in self._stubs: + self._stubs['import_attached_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/ImportAttachedCluster', + request_serializer=attached_service.ImportAttachedClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_attached_cluster'] + + @property + def get_attached_cluster(self) -> Callable[ + [attached_service.GetAttachedClusterRequest], + attached_resources.AttachedCluster]: + r"""Return a callable for the get attached cluster method over gRPC. + + Describes a specific + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource. + + Returns: + Callable[[~.GetAttachedClusterRequest], + ~.AttachedCluster]: + 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_attached_cluster' not in self._stubs: + self._stubs['get_attached_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/GetAttachedCluster', + request_serializer=attached_service.GetAttachedClusterRequest.serialize, + response_deserializer=attached_resources.AttachedCluster.deserialize, + ) + return self._stubs['get_attached_cluster'] + + @property + def list_attached_clusters(self) -> Callable[ + [attached_service.ListAttachedClustersRequest], + attached_service.ListAttachedClustersResponse]: + r"""Return a callable for the list attached clusters method over gRPC. + + Lists all + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resources on a given Google Cloud project and region. + + Returns: + Callable[[~.ListAttachedClustersRequest], + ~.ListAttachedClustersResponse]: + 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_attached_clusters' not in self._stubs: + self._stubs['list_attached_clusters'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/ListAttachedClusters', + request_serializer=attached_service.ListAttachedClustersRequest.serialize, + response_deserializer=attached_service.ListAttachedClustersResponse.deserialize, + ) + return self._stubs['list_attached_clusters'] + + @property + def delete_attached_cluster(self) -> Callable[ + [attached_service.DeleteAttachedClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete attached cluster method over gRPC. + + Deletes a specific + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAttachedClusterRequest], + ~.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_attached_cluster' not in self._stubs: + self._stubs['delete_attached_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/DeleteAttachedCluster', + request_serializer=attached_service.DeleteAttachedClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_attached_cluster'] + + @property + def get_attached_server_config(self) -> Callable[ + [attached_service.GetAttachedServerConfigRequest], + attached_resources.AttachedServerConfig]: + r"""Return a callable for the get attached server config method over gRPC. + + Returns information, such as supported Kubernetes + versions, on a given Google Cloud location. + + Returns: + Callable[[~.GetAttachedServerConfigRequest], + ~.AttachedServerConfig]: + 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_attached_server_config' not in self._stubs: + self._stubs['get_attached_server_config'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/GetAttachedServerConfig', + request_serializer=attached_service.GetAttachedServerConfigRequest.serialize, + response_deserializer=attached_resources.AttachedServerConfig.deserialize, + ) + return self._stubs['get_attached_server_config'] + + @property + def generate_attached_cluster_install_manifest(self) -> Callable[ + [attached_service.GenerateAttachedClusterInstallManifestRequest], + attached_service.GenerateAttachedClusterInstallManifestResponse]: + r"""Return a callable for the generate attached cluster + install manifest method over gRPC. + + Generates the install manifest to be installed on the + target cluster. + + Returns: + Callable[[~.GenerateAttachedClusterInstallManifestRequest], + ~.GenerateAttachedClusterInstallManifestResponse]: + 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_attached_cluster_install_manifest' not in self._stubs: + self._stubs['generate_attached_cluster_install_manifest'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/GenerateAttachedClusterInstallManifest', + request_serializer=attached_service.GenerateAttachedClusterInstallManifestRequest.serialize, + response_deserializer=attached_service.GenerateAttachedClusterInstallManifestResponse.deserialize, + ) + return self._stubs['generate_attached_cluster_install_manifest'] + + @property + def generate_attached_cluster_agent_token(self) -> Callable[ + [attached_service.GenerateAttachedClusterAgentTokenRequest], + attached_service.GenerateAttachedClusterAgentTokenResponse]: + r"""Return a callable for the generate attached cluster + agent token method over gRPC. + + Generates an access token for a cluster agent. + + Returns: + Callable[[~.GenerateAttachedClusterAgentTokenRequest], + ~.GenerateAttachedClusterAgentTokenResponse]: + 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_attached_cluster_agent_token' not in self._stubs: + self._stubs['generate_attached_cluster_agent_token'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/GenerateAttachedClusterAgentToken', + request_serializer=attached_service.GenerateAttachedClusterAgentTokenRequest.serialize, + response_deserializer=attached_service.GenerateAttachedClusterAgentTokenResponse.deserialize, + ) + return self._stubs['generate_attached_cluster_agent_token'] + + def close(self): + self._logged_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._logged_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._logged_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._logged_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._logged_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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AttachedClustersGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc_asyncio.py new file mode 100644 index 000000000000..937686a8132b --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc_asyncio.py @@ -0,0 +1,804 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.gke_multicloud_v1.types import attached_resources +from google.cloud.gke_multicloud_v1.types import attached_service +from google.longrunning import operations_pb2 # type: ignore +from .base import AttachedClustersTransport, DEFAULT_CLIENT_INFO +from .grpc import AttachedClustersGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AttachedClustersGrpcAsyncIOTransport(AttachedClustersTransport): + """gRPC AsyncIO backend transport for AttachedClusters. + + The AttachedClusters API provides a single centrally managed + service to register and manage Anthos attached clusters that run + on customer's owned infrastructure. + + 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 = 'gkemulticloud.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'gkemulticloud.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_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._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_attached_cluster(self) -> Callable[ + [attached_service.CreateAttachedClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create attached cluster method over gRPC. + + Creates a new + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAttachedClusterRequest], + 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_attached_cluster' not in self._stubs: + self._stubs['create_attached_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/CreateAttachedCluster', + request_serializer=attached_service.CreateAttachedClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_attached_cluster'] + + @property + def update_attached_cluster(self) -> Callable[ + [attached_service.UpdateAttachedClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update attached cluster method over gRPC. + + Updates an + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. + + Returns: + Callable[[~.UpdateAttachedClusterRequest], + 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_attached_cluster' not in self._stubs: + self._stubs['update_attached_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/UpdateAttachedCluster', + request_serializer=attached_service.UpdateAttachedClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_attached_cluster'] + + @property + def import_attached_cluster(self) -> Callable[ + [attached_service.ImportAttachedClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import attached cluster method over gRPC. + + Imports creates a new + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource by importing an existing Fleet Membership resource. + + Attached Clusters created before the introduction of the Anthos + Multi-Cloud API can be imported through this method. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.ImportAttachedClusterRequest], + 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 'import_attached_cluster' not in self._stubs: + self._stubs['import_attached_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/ImportAttachedCluster', + request_serializer=attached_service.ImportAttachedClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_attached_cluster'] + + @property + def get_attached_cluster(self) -> Callable[ + [attached_service.GetAttachedClusterRequest], + Awaitable[attached_resources.AttachedCluster]]: + r"""Return a callable for the get attached cluster method over gRPC. + + Describes a specific + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource. + + Returns: + Callable[[~.GetAttachedClusterRequest], + Awaitable[~.AttachedCluster]]: + 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_attached_cluster' not in self._stubs: + self._stubs['get_attached_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/GetAttachedCluster', + request_serializer=attached_service.GetAttachedClusterRequest.serialize, + response_deserializer=attached_resources.AttachedCluster.deserialize, + ) + return self._stubs['get_attached_cluster'] + + @property + def list_attached_clusters(self) -> Callable[ + [attached_service.ListAttachedClustersRequest], + Awaitable[attached_service.ListAttachedClustersResponse]]: + r"""Return a callable for the list attached clusters method over gRPC. + + Lists all + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resources on a given Google Cloud project and region. + + Returns: + Callable[[~.ListAttachedClustersRequest], + Awaitable[~.ListAttachedClustersResponse]]: + 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_attached_clusters' not in self._stubs: + self._stubs['list_attached_clusters'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/ListAttachedClusters', + request_serializer=attached_service.ListAttachedClustersRequest.serialize, + response_deserializer=attached_service.ListAttachedClustersResponse.deserialize, + ) + return self._stubs['list_attached_clusters'] + + @property + def delete_attached_cluster(self) -> Callable[ + [attached_service.DeleteAttachedClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete attached cluster method over gRPC. + + Deletes a specific + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAttachedClusterRequest], + 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_attached_cluster' not in self._stubs: + self._stubs['delete_attached_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/DeleteAttachedCluster', + request_serializer=attached_service.DeleteAttachedClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_attached_cluster'] + + @property + def get_attached_server_config(self) -> Callable[ + [attached_service.GetAttachedServerConfigRequest], + Awaitable[attached_resources.AttachedServerConfig]]: + r"""Return a callable for the get attached server config method over gRPC. + + Returns information, such as supported Kubernetes + versions, on a given Google Cloud location. + + Returns: + Callable[[~.GetAttachedServerConfigRequest], + Awaitable[~.AttachedServerConfig]]: + 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_attached_server_config' not in self._stubs: + self._stubs['get_attached_server_config'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/GetAttachedServerConfig', + request_serializer=attached_service.GetAttachedServerConfigRequest.serialize, + response_deserializer=attached_resources.AttachedServerConfig.deserialize, + ) + return self._stubs['get_attached_server_config'] + + @property + def generate_attached_cluster_install_manifest(self) -> Callable[ + [attached_service.GenerateAttachedClusterInstallManifestRequest], + Awaitable[attached_service.GenerateAttachedClusterInstallManifestResponse]]: + r"""Return a callable for the generate attached cluster + install manifest method over gRPC. + + Generates the install manifest to be installed on the + target cluster. + + Returns: + Callable[[~.GenerateAttachedClusterInstallManifestRequest], + Awaitable[~.GenerateAttachedClusterInstallManifestResponse]]: + 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_attached_cluster_install_manifest' not in self._stubs: + self._stubs['generate_attached_cluster_install_manifest'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/GenerateAttachedClusterInstallManifest', + request_serializer=attached_service.GenerateAttachedClusterInstallManifestRequest.serialize, + response_deserializer=attached_service.GenerateAttachedClusterInstallManifestResponse.deserialize, + ) + return self._stubs['generate_attached_cluster_install_manifest'] + + @property + def generate_attached_cluster_agent_token(self) -> Callable[ + [attached_service.GenerateAttachedClusterAgentTokenRequest], + Awaitable[attached_service.GenerateAttachedClusterAgentTokenResponse]]: + r"""Return a callable for the generate attached cluster + agent token method over gRPC. + + Generates an access token for a cluster agent. + + Returns: + Callable[[~.GenerateAttachedClusterAgentTokenRequest], + Awaitable[~.GenerateAttachedClusterAgentTokenResponse]]: + 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_attached_cluster_agent_token' not in self._stubs: + self._stubs['generate_attached_cluster_agent_token'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AttachedClusters/GenerateAttachedClusterAgentToken', + request_serializer=attached_service.GenerateAttachedClusterAgentTokenRequest.serialize, + response_deserializer=attached_service.GenerateAttachedClusterAgentTokenResponse.deserialize, + ) + return self._stubs['generate_attached_cluster_agent_token'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_attached_cluster: self._wrap_method( + self.create_attached_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_attached_cluster: self._wrap_method( + self.update_attached_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.import_attached_cluster: self._wrap_method( + self.import_attached_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_attached_cluster: self._wrap_method( + self.get_attached_cluster, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_attached_clusters: self._wrap_method( + self.list_attached_clusters, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_attached_cluster: self._wrap_method( + self.delete_attached_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_attached_server_config: self._wrap_method( + self.get_attached_server_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_attached_cluster_install_manifest: self._wrap_method( + self.generate_attached_cluster_install_manifest, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_attached_cluster_agent_token: self._wrap_method( + self.generate_attached_cluster_agent_token, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @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._logged_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._logged_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._logged_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._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'AttachedClustersGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest.py new file mode 100644 index 000000000000..521ec7afd435 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest.py @@ -0,0 +1,2131 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # 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 gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.gke_multicloud_v1.types import attached_resources +from google.cloud.gke_multicloud_v1.types import attached_service +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseAttachedClustersRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class AttachedClustersRestInterceptor: + """Interceptor for AttachedClusters. + + 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 AttachedClustersRestTransport. + + .. code-block:: python + class MyCustomAttachedClustersInterceptor(AttachedClustersRestInterceptor): + def pre_create_attached_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_attached_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_attached_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_attached_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_attached_cluster_agent_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_attached_cluster_agent_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_attached_cluster_install_manifest(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_attached_cluster_install_manifest(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_attached_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_attached_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_attached_server_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_attached_server_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_attached_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_attached_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_attached_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_attached_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_attached_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_attached_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AttachedClustersRestTransport(interceptor=MyCustomAttachedClustersInterceptor()) + client = AttachedClustersClient(transport=transport) + + + """ + def pre_create_attached_cluster(self, request: attached_service.CreateAttachedClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.CreateAttachedClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_attached_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters server. + """ + return request, metadata + + def post_create_attached_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_attached_cluster + + Override in a subclass to manipulate the response + after it is returned by the AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_delete_attached_cluster(self, request: attached_service.DeleteAttachedClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.DeleteAttachedClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_attached_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters server. + """ + return request, metadata + + def post_delete_attached_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_attached_cluster + + Override in a subclass to manipulate the response + after it is returned by the AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_generate_attached_cluster_agent_token(self, request: attached_service.GenerateAttachedClusterAgentTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.GenerateAttachedClusterAgentTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for generate_attached_cluster_agent_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters server. + """ + return request, metadata + + def post_generate_attached_cluster_agent_token(self, response: attached_service.GenerateAttachedClusterAgentTokenResponse) -> attached_service.GenerateAttachedClusterAgentTokenResponse: + """Post-rpc interceptor for generate_attached_cluster_agent_token + + Override in a subclass to manipulate the response + after it is returned by the AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_generate_attached_cluster_install_manifest(self, request: attached_service.GenerateAttachedClusterInstallManifestRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.GenerateAttachedClusterInstallManifestRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for generate_attached_cluster_install_manifest + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters server. + """ + return request, metadata + + def post_generate_attached_cluster_install_manifest(self, response: attached_service.GenerateAttachedClusterInstallManifestResponse) -> attached_service.GenerateAttachedClusterInstallManifestResponse: + """Post-rpc interceptor for generate_attached_cluster_install_manifest + + Override in a subclass to manipulate the response + after it is returned by the AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_get_attached_cluster(self, request: attached_service.GetAttachedClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.GetAttachedClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_attached_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters server. + """ + return request, metadata + + def post_get_attached_cluster(self, response: attached_resources.AttachedCluster) -> attached_resources.AttachedCluster: + """Post-rpc interceptor for get_attached_cluster + + Override in a subclass to manipulate the response + after it is returned by the AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_get_attached_server_config(self, request: attached_service.GetAttachedServerConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.GetAttachedServerConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_attached_server_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters server. + """ + return request, metadata + + def post_get_attached_server_config(self, response: attached_resources.AttachedServerConfig) -> attached_resources.AttachedServerConfig: + """Post-rpc interceptor for get_attached_server_config + + Override in a subclass to manipulate the response + after it is returned by the AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_import_attached_cluster(self, request: attached_service.ImportAttachedClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.ImportAttachedClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for import_attached_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters server. + """ + return request, metadata + + def post_import_attached_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for import_attached_cluster + + Override in a subclass to manipulate the response + after it is returned by the AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_list_attached_clusters(self, request: attached_service.ListAttachedClustersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.ListAttachedClustersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_attached_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters server. + """ + return request, metadata + + def post_list_attached_clusters(self, response: attached_service.ListAttachedClustersResponse) -> attached_service.ListAttachedClustersResponse: + """Post-rpc interceptor for list_attached_clusters + + Override in a subclass to manipulate the response + after it is returned by the AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_update_attached_cluster(self, request: attached_service.UpdateAttachedClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.UpdateAttachedClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_attached_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters server. + """ + return request, metadata + + def post_update_attached_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_attached_cluster + + Override in a subclass to manipulate the response + after it is returned by the AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters 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 AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters 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 AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters 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 AttachedClusters server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AttachedClusters 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 AttachedClusters server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AttachedClustersRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AttachedClustersRestInterceptor + + +class AttachedClustersRestTransport(_BaseAttachedClustersRestTransport): + """REST backend synchronous transport for AttachedClusters. + + The AttachedClusters API provides a single centrally managed + service to register and manage Anthos attached clusters that run + on customer's owned infrastructure. + + 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 = 'gkemulticloud.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[AttachedClustersRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + 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 AttachedClustersRestInterceptor() + 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 _CreateAttachedCluster(_BaseAttachedClustersRestTransport._BaseCreateAttachedCluster, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.CreateAttachedCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: attached_service.CreateAttachedClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create attached cluster method over HTTP. + + Args: + request (~.attached_service.CreateAttachedClusterRequest): + The request object. Request message for + ``AttachedClusters.CreateAttachedCluster`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAttachedClustersRestTransport._BaseCreateAttachedCluster._get_http_options() + + request, metadata = self._interceptor.pre_create_attached_cluster(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseCreateAttachedCluster._get_transcoded_request(http_options, request) + + body = _BaseAttachedClustersRestTransport._BaseCreateAttachedCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseCreateAttachedCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.CreateAttachedCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "CreateAttachedCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._CreateAttachedCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_attached_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.create_attached_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "CreateAttachedCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAttachedCluster(_BaseAttachedClustersRestTransport._BaseDeleteAttachedCluster, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.DeleteAttachedCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: attached_service.DeleteAttachedClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete attached cluster method over HTTP. + + Args: + request (~.attached_service.DeleteAttachedClusterRequest): + The request object. Request message for + ``AttachedClusters.DeleteAttachedCluster`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAttachedClustersRestTransport._BaseDeleteAttachedCluster._get_http_options() + + request, metadata = self._interceptor.pre_delete_attached_cluster(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseDeleteAttachedCluster._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseDeleteAttachedCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.DeleteAttachedCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "DeleteAttachedCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._DeleteAttachedCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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_attached_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.delete_attached_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "DeleteAttachedCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateAttachedClusterAgentToken(_BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.GenerateAttachedClusterAgentToken") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: attached_service.GenerateAttachedClusterAgentTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> attached_service.GenerateAttachedClusterAgentTokenResponse: + r"""Call the generate attached cluster + agent token method over HTTP. + + Args: + request (~.attached_service.GenerateAttachedClusterAgentTokenRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.attached_service.GenerateAttachedClusterAgentTokenResponse: + + """ + + http_options = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken._get_http_options() + + request, metadata = self._interceptor.pre_generate_attached_cluster_agent_token(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken._get_transcoded_request(http_options, request) + + body = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.GenerateAttachedClusterAgentToken", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "GenerateAttachedClusterAgentToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._GenerateAttachedClusterAgentToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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 = attached_service.GenerateAttachedClusterAgentTokenResponse() + pb_resp = attached_service.GenerateAttachedClusterAgentTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_attached_cluster_agent_token(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = attached_service.GenerateAttachedClusterAgentTokenResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.generate_attached_cluster_agent_token", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "GenerateAttachedClusterAgentToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateAttachedClusterInstallManifest(_BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterInstallManifest, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.GenerateAttachedClusterInstallManifest") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: attached_service.GenerateAttachedClusterInstallManifestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> attached_service.GenerateAttachedClusterInstallManifestResponse: + r"""Call the generate attached cluster + install manifest method over HTTP. + + Args: + request (~.attached_service.GenerateAttachedClusterInstallManifestRequest): + The request object. Request message for + ``AttachedClusters.GenerateAttachedClusterInstallManifest`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.attached_service.GenerateAttachedClusterInstallManifestResponse: + Response message for + ``AttachedClusters.GenerateAttachedClusterInstallManifest`` + method. + + """ + + http_options = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterInstallManifest._get_http_options() + + request, metadata = self._interceptor.pre_generate_attached_cluster_install_manifest(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterInstallManifest._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterInstallManifest._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.GenerateAttachedClusterInstallManifest", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "GenerateAttachedClusterInstallManifest", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._GenerateAttachedClusterInstallManifest._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = attached_service.GenerateAttachedClusterInstallManifestResponse() + pb_resp = attached_service.GenerateAttachedClusterInstallManifestResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_attached_cluster_install_manifest(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = attached_service.GenerateAttachedClusterInstallManifestResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.generate_attached_cluster_install_manifest", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "GenerateAttachedClusterInstallManifest", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAttachedCluster(_BaseAttachedClustersRestTransport._BaseGetAttachedCluster, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.GetAttachedCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: attached_service.GetAttachedClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> attached_resources.AttachedCluster: + r"""Call the get attached cluster method over HTTP. + + Args: + request (~.attached_service.GetAttachedClusterRequest): + The request object. Request message for + ``AttachedClusters.GetAttachedCluster`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.attached_resources.AttachedCluster: + An Anthos cluster running on customer + own infrastructure. + + """ + + http_options = _BaseAttachedClustersRestTransport._BaseGetAttachedCluster._get_http_options() + + request, metadata = self._interceptor.pre_get_attached_cluster(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseGetAttachedCluster._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseGetAttachedCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.GetAttachedCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "GetAttachedCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._GetAttachedCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = attached_resources.AttachedCluster() + pb_resp = attached_resources.AttachedCluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_attached_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = attached_resources.AttachedCluster.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.get_attached_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "GetAttachedCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAttachedServerConfig(_BaseAttachedClustersRestTransport._BaseGetAttachedServerConfig, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.GetAttachedServerConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: attached_service.GetAttachedServerConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> attached_resources.AttachedServerConfig: + r"""Call the get attached server + config method over HTTP. + + Args: + request (~.attached_service.GetAttachedServerConfigRequest): + The request object. GetAttachedServerConfigRequest gets + the server config for attached clusters. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.attached_resources.AttachedServerConfig: + AttachedServerConfig provides + information about supported Kubernetes + versions + + """ + + http_options = _BaseAttachedClustersRestTransport._BaseGetAttachedServerConfig._get_http_options() + + request, metadata = self._interceptor.pre_get_attached_server_config(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseGetAttachedServerConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseGetAttachedServerConfig._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.GetAttachedServerConfig", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "GetAttachedServerConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._GetAttachedServerConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = attached_resources.AttachedServerConfig() + pb_resp = attached_resources.AttachedServerConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_attached_server_config(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = attached_resources.AttachedServerConfig.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.get_attached_server_config", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "GetAttachedServerConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ImportAttachedCluster(_BaseAttachedClustersRestTransport._BaseImportAttachedCluster, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.ImportAttachedCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: attached_service.ImportAttachedClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the import attached cluster method over HTTP. + + Args: + request (~.attached_service.ImportAttachedClusterRequest): + The request object. Request message for + ``AttachedClusters.ImportAttachedCluster`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAttachedClustersRestTransport._BaseImportAttachedCluster._get_http_options() + + request, metadata = self._interceptor.pre_import_attached_cluster(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseImportAttachedCluster._get_transcoded_request(http_options, request) + + body = _BaseAttachedClustersRestTransport._BaseImportAttachedCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseImportAttachedCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.ImportAttachedCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "ImportAttachedCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._ImportAttachedCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_import_attached_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.import_attached_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "ImportAttachedCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAttachedClusters(_BaseAttachedClustersRestTransport._BaseListAttachedClusters, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.ListAttachedClusters") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: attached_service.ListAttachedClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> attached_service.ListAttachedClustersResponse: + r"""Call the list attached clusters method over HTTP. + + Args: + request (~.attached_service.ListAttachedClustersRequest): + The request object. Request message for + ``AttachedClusters.ListAttachedClusters`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.attached_service.ListAttachedClustersResponse: + Response message for + ``AttachedClusters.ListAttachedClusters`` method. + + """ + + http_options = _BaseAttachedClustersRestTransport._BaseListAttachedClusters._get_http_options() + + request, metadata = self._interceptor.pre_list_attached_clusters(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseListAttachedClusters._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseListAttachedClusters._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.ListAttachedClusters", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "ListAttachedClusters", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._ListAttachedClusters._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = attached_service.ListAttachedClustersResponse() + pb_resp = attached_service.ListAttachedClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_attached_clusters(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = attached_service.ListAttachedClustersResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.list_attached_clusters", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "ListAttachedClusters", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAttachedCluster(_BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.UpdateAttachedCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: attached_service.UpdateAttachedClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update attached cluster method over HTTP. + + Args: + request (~.attached_service.UpdateAttachedClusterRequest): + The request object. Request message for + ``AttachedClusters.UpdateAttachedCluster`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster._get_http_options() + + request, metadata = self._interceptor.pre_update_attached_cluster(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster._get_transcoded_request(http_options, request) + + body = _BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.UpdateAttachedCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "UpdateAttachedCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._UpdateAttachedCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_attached_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.update_attached_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "UpdateAttachedCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_attached_cluster(self) -> Callable[ + [attached_service.CreateAttachedClusterRequest], + 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._CreateAttachedCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_attached_cluster(self) -> Callable[ + [attached_service.DeleteAttachedClusterRequest], + 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._DeleteAttachedCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_attached_cluster_agent_token(self) -> Callable[ + [attached_service.GenerateAttachedClusterAgentTokenRequest], + attached_service.GenerateAttachedClusterAgentTokenResponse]: + # 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._GenerateAttachedClusterAgentToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_attached_cluster_install_manifest(self) -> Callable[ + [attached_service.GenerateAttachedClusterInstallManifestRequest], + attached_service.GenerateAttachedClusterInstallManifestResponse]: + # 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._GenerateAttachedClusterInstallManifest(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_attached_cluster(self) -> Callable[ + [attached_service.GetAttachedClusterRequest], + attached_resources.AttachedCluster]: + # 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._GetAttachedCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_attached_server_config(self) -> Callable[ + [attached_service.GetAttachedServerConfigRequest], + attached_resources.AttachedServerConfig]: + # 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._GetAttachedServerConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_attached_cluster(self) -> Callable[ + [attached_service.ImportAttachedClusterRequest], + 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._ImportAttachedCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_attached_clusters(self) -> Callable[ + [attached_service.ListAttachedClustersRequest], + attached_service.ListAttachedClustersResponse]: + # 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._ListAttachedClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_attached_cluster(self) -> Callable[ + [attached_service.UpdateAttachedClusterRequest], + 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._UpdateAttachedCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseAttachedClustersRestTransport._BaseCancelOperation, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAttachedClustersRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseAttachedClustersRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.CancelOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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(_BaseAttachedClustersRestTransport._BaseDeleteOperation, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAttachedClustersRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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(_BaseAttachedClustersRestTransport._BaseGetOperation, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseAttachedClustersRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.GetOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseAttachedClustersRestTransport._BaseListOperations, AttachedClustersRestStub): + def __hash__(self): + return hash("AttachedClustersRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseAttachedClustersRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseAttachedClustersRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAttachedClustersRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.ListOperations", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AttachedClustersRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AttachedClustersAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AttachedClustersRestTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest_base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest_base.py new file mode 100644 index 000000000000..5ee95d700095 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest_base.py @@ -0,0 +1,562 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import AttachedClustersTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.gke_multicloud_v1.types import attached_resources +from google.cloud.gke_multicloud_v1.types import attached_service +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseAttachedClustersRestTransport(AttachedClustersTransport): + """Base REST backend transport for AttachedClusters. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 = 'gkemulticloud.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[Any]): 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. + 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 + 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 + ) + + class _BaseCreateAttachedCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "attachedClusterId" : "", } + + @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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/attachedClusters', + 'body': 'attached_cluster', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = attached_service.CreateAttachedClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAttachedClustersRestTransport._BaseCreateAttachedCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseDeleteAttachedCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/attachedClusters/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = attached_service.DeleteAttachedClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAttachedClustersRestTransport._BaseDeleteAttachedCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGenerateAttachedClusterAgentToken: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{attached_cluster=projects/*/locations/*/attachedClusters/*}:generateAttachedClusterAgentToken', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = attached_service.GenerateAttachedClusterAgentTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGenerateAttachedClusterInstallManifest: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "attachedClusterId" : "", "platformVersion" : "", } + + @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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}:generateAttachedClusterInstallManifest', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = attached_service.GenerateAttachedClusterInstallManifestRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterInstallManifest._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAttachedCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/attachedClusters/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = attached_service.GetAttachedClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAttachedClustersRestTransport._BaseGetAttachedCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAttachedServerConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/attachedServerConfig}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = attached_service.GetAttachedServerConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAttachedClustersRestTransport._BaseGetAttachedServerConfig._get_unset_required_fields(query_params)) + + return query_params + + class _BaseImportAttachedCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/attachedClusters:import', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = attached_service.ImportAttachedClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAttachedClustersRestTransport._BaseImportAttachedCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseListAttachedClusters: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/attachedClusters', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = attached_service.ListAttachedClustersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAttachedClustersRestTransport._BaseListAttachedClusters._get_unset_required_fields(query_params)) + + return query_params + + class _BaseUpdateAttachedCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{attached_cluster.name=projects/*/locations/*/attachedClusters/*}', + 'body': 'attached_cluster', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = attached_service.UpdateAttachedClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseAttachedClustersRestTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/__init__.py new file mode 100644 index 000000000000..123c91fd9705 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AwsClustersClient +from .async_client import AwsClustersAsyncClient + +__all__ = ( + 'AwsClustersClient', + 'AwsClustersAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/async_client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/async_client.py new file mode 100644 index 000000000000..0a7ee98c245a --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/async_client.py @@ -0,0 +1,2561 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.gke_multicloud_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.gke_multicloud_v1.services.aws_clusters import pagers +from google.cloud.gke_multicloud_v1.types import aws_resources +from google.cloud.gke_multicloud_v1.types import aws_service +from google.cloud.gke_multicloud_v1.types import common_resources +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AwsClustersTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AwsClustersGrpcAsyncIOTransport +from .client import AwsClustersClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class AwsClustersAsyncClient: + """The AwsClusters API provides a single centrally managed + service to create and manage Anthos clusters that run on AWS + infrastructure. + """ + + _client: AwsClustersClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AwsClustersClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AwsClustersClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AwsClustersClient._DEFAULT_UNIVERSE + + aws_cluster_path = staticmethod(AwsClustersClient.aws_cluster_path) + parse_aws_cluster_path = staticmethod(AwsClustersClient.parse_aws_cluster_path) + aws_node_pool_path = staticmethod(AwsClustersClient.aws_node_pool_path) + parse_aws_node_pool_path = staticmethod(AwsClustersClient.parse_aws_node_pool_path) + aws_server_config_path = staticmethod(AwsClustersClient.aws_server_config_path) + parse_aws_server_config_path = staticmethod(AwsClustersClient.parse_aws_server_config_path) + common_billing_account_path = staticmethod(AwsClustersClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AwsClustersClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AwsClustersClient.common_folder_path) + parse_common_folder_path = staticmethod(AwsClustersClient.parse_common_folder_path) + common_organization_path = staticmethod(AwsClustersClient.common_organization_path) + parse_common_organization_path = staticmethod(AwsClustersClient.parse_common_organization_path) + common_project_path = staticmethod(AwsClustersClient.common_project_path) + parse_common_project_path = staticmethod(AwsClustersClient.parse_common_project_path) + common_location_path = staticmethod(AwsClustersClient.common_location_path) + parse_common_location_path = staticmethod(AwsClustersClient.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: + AwsClustersAsyncClient: The constructed client. + """ + return AwsClustersClient.from_service_account_info.__func__(AwsClustersAsyncClient, 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: + AwsClustersAsyncClient: The constructed client. + """ + return AwsClustersClient.from_service_account_file.__func__(AwsClustersAsyncClient, 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 AwsClustersClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AwsClustersTransport: + """Returns the transport used by the client instance. + + Returns: + AwsClustersTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = AwsClustersClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AwsClustersTransport, Callable[..., AwsClustersTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the aws clusters async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AwsClustersTransport,Callable[..., AwsClustersTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AwsClustersTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AwsClustersClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.gkemulticloud_v1.AwsClustersAsyncClient`.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "credentialsType": None, + } + ) + + async def create_aws_cluster(self, + request: Optional[Union[aws_service.CreateAwsClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + aws_cluster: Optional[aws_resources.AwsCluster] = None, + aws_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource + on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_create_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + aws_cluster = gke_multicloud_v1.AwsCluster() + aws_cluster.networking.vpc_id = "vpc_id_value" + aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + aws_cluster.aws_region = "aws_region_value" + aws_cluster.control_plane.version = "version_value" + aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] + aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" + aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" + aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAwsClusterRequest( + parent="parent_value", + aws_cluster=aws_cluster, + aws_cluster_id="aws_cluster_id_value", + ) + + # Make the request + operation = client.create_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAwsClusterRequest, dict]]): + The request object. Request message for ``AwsClusters.CreateAwsCluster`` + method. + parent (:class:`str`): + Required. The parent location where this + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + aws_cluster (:class:`google.cloud.gke_multicloud_v1.types.AwsCluster`): + Required. The specification of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + to create. + + This corresponds to the ``aws_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + aws_cluster_id (:class:`str`): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource name formatted as + ``projects//locations//awsClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``aws_cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AwsCluster` + An Anthos cluster running on AWS. + + """ + # 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, aws_cluster, aws_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.CreateAwsClusterRequest): + request = aws_service.CreateAwsClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if aws_cluster is not None: + request.aws_cluster = aws_cluster + if aws_cluster_id is not None: + request.aws_cluster_id = aws_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_aws_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + aws_resources.AwsCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_aws_cluster(self, + request: Optional[Union[aws_service.UpdateAwsClusterRequest, dict]] = None, + *, + aws_cluster: Optional[aws_resources.AwsCluster] = 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, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + .. 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 gke_multicloud_v1 + + async def sample_update_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + aws_cluster = gke_multicloud_v1.AwsCluster() + aws_cluster.networking.vpc_id = "vpc_id_value" + aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + aws_cluster.aws_region = "aws_region_value" + aws_cluster.control_plane.version = "version_value" + aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] + aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" + aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" + aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAwsClusterRequest( + aws_cluster=aws_cluster, + ) + + # Make the request + operation = client.update_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.UpdateAwsClusterRequest, dict]]): + The request object. Request message for ``AwsClusters.UpdateAwsCluster`` + method. + aws_cluster (:class:`google.cloud.gke_multicloud_v1.types.AwsCluster`): + Required. The + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource to update. + + This corresponds to the ``aws_cluster`` 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 path + must be supplied in this field. The elements of the + repeated paths field can only include these fields from + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]: + + - ``description``. + - ``annotations``. + - ``control_plane.version``. + - ``authorization.admin_users``. + - ``authorization.admin_groups``. + - ``binary_authorization.evaluation_mode``. + - ``control_plane.aws_services_authentication.role_arn``. + - ``control_plane.aws_services_authentication.role_session_name``. + - ``control_plane.config_encryption.kms_key_arn``. + - ``control_plane.instance_type``. + - ``control_plane.security_group_ids``. + - ``control_plane.proxy_config``. + - ``control_plane.proxy_config.secret_arn``. + - ``control_plane.proxy_config.secret_version``. + - ``control_plane.root_volume.size_gib``. + - ``control_plane.root_volume.volume_type``. + - ``control_plane.root_volume.iops``. + - ``control_plane.root_volume.throughput``. + - ``control_plane.root_volume.kms_key_arn``. + - ``control_plane.ssh_config``. + - ``control_plane.ssh_config.ec2_key_pair``. + - ``control_plane.instance_placement.tenancy``. + - ``control_plane.iam_instance_profile``. + - ``logging_config.component_config.enable_components``. + - ``control_plane.tags``. + - ``monitoring_config.managed_prometheus_config.enabled``. + - ``networking.per_node_pool_sg_rules_disabled``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AwsCluster` + An Anthos cluster running on AWS. + + """ + # 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([aws_cluster, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.UpdateAwsClusterRequest): + request = aws_service.UpdateAwsClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if aws_cluster is not None: + request.aws_cluster = aws_cluster + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_aws_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_cluster.name", request.aws_cluster.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + aws_resources.AwsCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_aws_cluster(self, + request: Optional[Union[aws_service.GetAwsClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_resources.AwsCluster: + r"""Describes a specific + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] 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 gke_multicloud_v1 + + async def sample_get_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_aws_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAwsClusterRequest, dict]]): + The request object. Request message for ``AwsClusters.GetAwsCluster`` + method. + name (:class:`str`): + Required. The name of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource to describe. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AwsCluster: + An Anthos cluster running on AWS. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GetAwsClusterRequest): + request = aws_service.GetAwsClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_aws_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_aws_clusters(self, + request: Optional[Union[aws_service.ListAwsClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAwsClustersAsyncPager: + r"""Lists all [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resources on a given Google Cloud project and region. + + .. 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 gke_multicloud_v1 + + async def sample_list_aws_clusters(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAwsClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_aws_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest, dict]]): + The request object. Request message for ``AwsClusters.ListAwsClusters`` + method. + parent (:class:`str`): + Required. The parent location which owns this collection + of + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsClustersAsyncPager: + Response message for AwsClusters.ListAwsClusters method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.ListAwsClustersRequest): + request = aws_service.ListAwsClustersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_aws_clusters] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAwsClustersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_aws_cluster(self, + request: Optional[Union[aws_service.DeleteAwsClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a specific + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. + + Fails if the cluster has one or more associated + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_delete_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAwsClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAwsClusterRequest, dict]]): + The request object. Request message for ``AwsClusters.DeleteAwsCluster`` + method. + name (:class:`str`): + Required. The resource name the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + to delete. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.DeleteAwsClusterRequest): + request = aws_service.DeleteAwsClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_aws_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_aws_cluster_agent_token(self, + request: Optional[Union[aws_service.GenerateAwsClusterAgentTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_service.GenerateAwsClusterAgentTokenResponse: + r"""Generates an access token for a cluster agent. + + .. 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 gke_multicloud_v1 + + async def sample_generate_aws_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAwsClusterAgentTokenRequest( + aws_cluster="aws_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = await client.generate_aws_cluster_agent_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenRequest, dict]]): + The request object. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenResponse: + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GenerateAwsClusterAgentTokenRequest): + request = aws_service.GenerateAwsClusterAgentTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_aws_cluster_agent_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_cluster", request.aws_cluster), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_aws_access_token(self, + request: Optional[Union[aws_service.GenerateAwsAccessTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_service.GenerateAwsAccessTokenResponse: + r"""Generates a short-lived access token to authenticate to a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] 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 gke_multicloud_v1 + + async def sample_generate_aws_access_token(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAwsAccessTokenRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = await client.generate_aws_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenRequest, dict]]): + The request object. Request message for + ``AwsClusters.GenerateAwsAccessToken`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenResponse: + Response message for AwsClusters.GenerateAwsAccessToken + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GenerateAwsAccessTokenRequest): + request = aws_service.GenerateAwsAccessTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_aws_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_cluster", request.aws_cluster), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_aws_node_pool(self, + request: Optional[Union[aws_service.CreateAwsNodePoolRequest, dict]] = None, + *, + parent: Optional[str] = None, + aws_node_pool: Optional[aws_resources.AwsNodePool] = None, + aws_node_pool_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool], + attached to a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_create_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + aws_node_pool = gke_multicloud_v1.AwsNodePool() + aws_node_pool.version = "version_value" + aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" + aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_node_pool.autoscaling.min_node_count = 1489 + aws_node_pool.autoscaling.max_node_count = 1491 + aws_node_pool.subnet_id = "subnet_id_value" + aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.CreateAwsNodePoolRequest( + parent="parent_value", + aws_node_pool=aws_node_pool, + aws_node_pool_id="aws_node_pool_id_value", + ) + + # Make the request + operation = client.create_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAwsNodePoolRequest, dict]]): + The request object. Response message for ``AwsClusters.CreateAwsNodePool`` + method. + parent (:class:`str`): + Required. The + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource where this node pool will be created. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + aws_node_pool (:class:`google.cloud.gke_multicloud_v1.types.AwsNodePool`): + Required. The specification of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + to create. + + This corresponds to the ``aws_node_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + aws_node_pool_id (:class:`str`): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource name formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``aws_node_pool_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AwsNodePool` + An Anthos node pool running on AWS. + + """ + # 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, aws_node_pool, aws_node_pool_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.CreateAwsNodePoolRequest): + request = aws_service.CreateAwsNodePoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if aws_node_pool is not None: + request.aws_node_pool = aws_node_pool + if aws_node_pool_id is not None: + request.aws_node_pool_id = aws_node_pool_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_aws_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + aws_resources.AwsNodePool, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_aws_node_pool(self, + request: Optional[Union[aws_service.UpdateAwsNodePoolRequest, dict]] = None, + *, + aws_node_pool: Optional[aws_resources.AwsNodePool] = 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, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. + + .. 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 gke_multicloud_v1 + + async def sample_update_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + aws_node_pool = gke_multicloud_v1.AwsNodePool() + aws_node_pool.version = "version_value" + aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" + aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_node_pool.autoscaling.min_node_count = 1489 + aws_node_pool.autoscaling.max_node_count = 1491 + aws_node_pool.subnet_id = "subnet_id_value" + aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.UpdateAwsNodePoolRequest( + aws_node_pool=aws_node_pool, + ) + + # Make the request + operation = client.update_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.UpdateAwsNodePoolRequest, dict]]): + The request object. Request message for ``AwsClusters.UpdateAwsNodePool`` + method. + aws_node_pool (:class:`google.cloud.gke_multicloud_v1.types.AwsNodePool`): + Required. The + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource to update. + + This corresponds to the ``aws_node_pool`` 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 path + must be supplied in this field. The elements of the + repeated paths field can only include these fields from + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]: + + - ``annotations``. + - ``version``. + - ``autoscaling.min_node_count``. + - ``autoscaling.max_node_count``. + - ``config.config_encryption.kms_key_arn``. + - ``config.security_group_ids``. + - ``config.root_volume.iops``. + - ``config.root_volume.throughput``. + - ``config.root_volume.kms_key_arn``. + - ``config.root_volume.volume_type``. + - ``config.root_volume.size_gib``. + - ``config.proxy_config``. + - ``config.proxy_config.secret_arn``. + - ``config.proxy_config.secret_version``. + - ``config.ssh_config``. + - ``config.ssh_config.ec2_key_pair``. + - ``config.instance_placement.tenancy``. + - ``config.iam_instance_profile``. + - ``config.labels``. + - ``config.tags``. + - ``config.autoscaling_metrics_collection``. + - ``config.autoscaling_metrics_collection.granularity``. + - ``config.autoscaling_metrics_collection.metrics``. + - ``config.instance_type``. + - ``management.auto_repair``. + - ``management``. + - ``update_settings``. + - ``update_settings.surge_settings``. + - ``update_settings.surge_settings.max_surge``. + - ``update_settings.surge_settings.max_unavailable``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AwsNodePool` + An Anthos node pool running on AWS. + + """ + # 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([aws_node_pool, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.UpdateAwsNodePoolRequest): + request = aws_service.UpdateAwsNodePoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if aws_node_pool is not None: + request.aws_node_pool = aws_node_pool + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_aws_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_node_pool.name", request.aws_node_pool.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + aws_resources.AwsNodePool, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def rollback_aws_node_pool_update(self, + request: Optional[Union[aws_service.RollbackAwsNodePoolUpdateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Rolls back a previously aborted or failed + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] update + request. Makes no changes if the last update request + successfully finished. If an update request is in progress, you + cannot rollback the update. You must first cancel or let it + finish unsuccessfully before you can rollback. + + .. 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 gke_multicloud_v1 + + async def sample_rollback_aws_node_pool_update(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.RollbackAwsNodePoolUpdateRequest( + name="name_value", + ) + + # Make the request + operation = client.rollback_aws_node_pool_update(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.RollbackAwsNodePoolUpdateRequest, dict]]): + The request object. Request message for + ``AwsClusters.RollbackAwsNodePoolUpdate`` method. + name (:class:`str`): + Required. The name of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource to rollback. + + ``AwsNodePool`` names are formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AwsNodePool` + An Anthos node pool running on AWS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.RollbackAwsNodePoolUpdateRequest): + request = aws_service.RollbackAwsNodePoolUpdateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.rollback_aws_node_pool_update] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + aws_resources.AwsNodePool, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_aws_node_pool(self, + request: Optional[Union[aws_service.GetAwsNodePoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_resources.AwsNodePool: + r"""Describes a specific + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + 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 gke_multicloud_v1 + + async def sample_get_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsNodePoolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_aws_node_pool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAwsNodePoolRequest, dict]]): + The request object. Request message for ``AwsClusters.GetAwsNodePool`` + method. + name (:class:`str`): + Required. The name of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource to describe. + + ``AwsNodePool`` names are formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AwsNodePool: + An Anthos node pool running on AWS. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GetAwsNodePoolRequest): + request = aws_service.GetAwsNodePoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_aws_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_aws_node_pools(self, + request: Optional[Union[aws_service.ListAwsNodePoolsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAwsNodePoolsAsyncPager: + r"""Lists all + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources on a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + .. 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 gke_multicloud_v1 + + async def sample_list_aws_node_pools(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAwsNodePoolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_aws_node_pools(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest, dict]]): + The request object. Request message for ``AwsClusters.ListAwsNodePools`` + method. + parent (:class:`str`): + Required. The parent ``AwsCluster`` which owns this + collection of + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsNodePoolsAsyncPager: + Response message for AwsClusters.ListAwsNodePools + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.ListAwsNodePoolsRequest): + request = aws_service.ListAwsNodePoolsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_aws_node_pools] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAwsNodePoolsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_aws_node_pool(self, + request: Optional[Union[aws_service.DeleteAwsNodePoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a specific + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_delete_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAwsNodePoolRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAwsNodePoolRequest, dict]]): + The request object. Request message for ``AwsClusters.DeleteAwsNodePool`` + method. + name (:class:`str`): + Required. The resource name the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + to delete. + + ``AwsNodePool`` names are formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.DeleteAwsNodePoolRequest): + request = aws_service.DeleteAwsNodePoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_aws_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_aws_open_id_config(self, + request: Optional[Union[aws_service.GetAwsOpenIdConfigRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_resources.AwsOpenIdConfig: + r"""Gets the OIDC discovery document for the cluster. See the + `OpenID Connect Discovery 1.0 + specification `__ + for details. + + .. 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 gke_multicloud_v1 + + async def sample_get_aws_open_id_config(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsOpenIdConfigRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = await client.get_aws_open_id_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAwsOpenIdConfigRequest, dict]]): + The request object. GetAwsOpenIdConfigRequest gets the + OIDC discovery document for the cluster. + See the OpenID Connect Discovery 1.0 + specification for details. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AwsOpenIdConfig: + AwsOpenIdConfig is an OIDC discovery + document for the cluster. See the OpenID + Connect Discovery 1.0 specification for + details. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GetAwsOpenIdConfigRequest): + request = aws_service.GetAwsOpenIdConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_aws_open_id_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_cluster", request.aws_cluster), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_aws_json_web_keys(self, + request: Optional[Union[aws_service.GetAwsJsonWebKeysRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_resources.AwsJsonWebKeys: + r"""Gets the public component of the cluster signing keys + in JSON Web Key format. + + .. 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 gke_multicloud_v1 + + async def sample_get_aws_json_web_keys(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsJsonWebKeysRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = await client.get_aws_json_web_keys(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAwsJsonWebKeysRequest, dict]]): + The request object. GetAwsJsonWebKeysRequest gets the public component of + the keys used by the cluster to sign token requests. + This will be the jwks_uri for the discover document + returned by getOpenIDConfig. See the OpenID Connect + Discovery 1.0 specification for details. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AwsJsonWebKeys: + AwsJsonWebKeys is a valid JSON Web + Key Set as specififed in RFC 7517. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GetAwsJsonWebKeysRequest): + request = aws_service.GetAwsJsonWebKeysRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_aws_json_web_keys] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_cluster", request.aws_cluster), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_aws_server_config(self, + request: Optional[Union[aws_service.GetAwsServerConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_resources.AwsServerConfig: + r"""Returns information, such as supported AWS regions + and Kubernetes versions, on a given Google Cloud + 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 gke_multicloud_v1 + + async def sample_get_aws_server_config(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsServerConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_aws_server_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAwsServerConfigRequest, dict]]): + The request object. GetAwsServerConfigRequest gets the + server config of GKE cluster on AWS. + name (:class:`str`): + Required. The name of the + [AwsServerConfig][google.cloud.gkemulticloud.v1.AwsServerConfig] + resource to describe. + + ``AwsServerConfig`` names are formatted as + ``projects//locations//awsServerConfig``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AwsServerConfig: + AwsServerConfig is the configuration + of GKE cluster on AWS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GetAwsServerConfigRequest): + request = aws_service.GetAwsServerConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_aws_server_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_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, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def 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, Union[str, bytes]]] = (), + ) -> 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + 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, Union[str, bytes]]] = (), + ) -> 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "AwsClustersAsyncClient": + 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__ = ( + "AwsClustersAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/client.py new file mode 100644 index 000000000000..6d1fbb83b1d7 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/client.py @@ -0,0 +1,2903 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.gke_multicloud_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.gke_multicloud_v1.services.aws_clusters import pagers +from google.cloud.gke_multicloud_v1.types import aws_resources +from google.cloud.gke_multicloud_v1.types import aws_service +from google.cloud.gke_multicloud_v1.types import common_resources +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AwsClustersTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AwsClustersGrpcTransport +from .transports.grpc_asyncio import AwsClustersGrpcAsyncIOTransport +from .transports.rest import AwsClustersRestTransport + + +class AwsClustersClientMeta(type): + """Metaclass for the AwsClusters 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[AwsClustersTransport]] + _transport_registry["grpc"] = AwsClustersGrpcTransport + _transport_registry["grpc_asyncio"] = AwsClustersGrpcAsyncIOTransport + _transport_registry["rest"] = AwsClustersRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AwsClustersTransport]: + """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 AwsClustersClient(metaclass=AwsClustersClientMeta): + """The AwsClusters API provides a single centrally managed + service to create and manage Anthos clusters that run on AWS + infrastructure. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "gkemulticloud.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "gkemulticloud.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AwsClustersClient: 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: + AwsClustersClient: 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) -> AwsClustersTransport: + """Returns the transport used by the client instance. + + Returns: + AwsClustersTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def aws_cluster_path(project: str,location: str,aws_cluster: str,) -> str: + """Returns a fully-qualified aws_cluster string.""" + return "projects/{project}/locations/{location}/awsClusters/{aws_cluster}".format(project=project, location=location, aws_cluster=aws_cluster, ) + + @staticmethod + def parse_aws_cluster_path(path: str) -> Dict[str,str]: + """Parses a aws_cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/awsClusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def aws_node_pool_path(project: str,location: str,aws_cluster: str,aws_node_pool: str,) -> str: + """Returns a fully-qualified aws_node_pool string.""" + return "projects/{project}/locations/{location}/awsClusters/{aws_cluster}/awsNodePools/{aws_node_pool}".format(project=project, location=location, aws_cluster=aws_cluster, aws_node_pool=aws_node_pool, ) + + @staticmethod + def parse_aws_node_pool_path(path: str) -> Dict[str,str]: + """Parses a aws_node_pool path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/awsClusters/(?P.+?)/awsNodePools/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def aws_server_config_path(project: str,location: str,) -> str: + """Returns a fully-qualified aws_server_config string.""" + return "projects/{project}/locations/{location}/awsServerConfig".format(project=project, location=location, ) + + @staticmethod + def parse_aws_server_config_path(path: str) -> Dict[str,str]: + """Parses a aws_server_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/awsServerConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = AwsClustersClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AwsClustersClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AwsClustersClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AwsClustersTransport, Callable[..., AwsClustersTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the aws clusters client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AwsClustersTransport,Callable[..., AwsClustersTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AwsClustersTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AwsClustersClient._read_environment_variables() + self._client_cert_source = AwsClustersClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AwsClustersClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AwsClustersTransport) + if transport_provided: + # transport is a AwsClustersTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(AwsClustersTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AwsClustersClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[AwsClustersTransport], Callable[..., AwsClustersTransport]] = ( + AwsClustersClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AwsClustersTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.gkemulticloud_v1.AwsClustersClient`.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "credentialsType": None, + } + ) + + def create_aws_cluster(self, + request: Optional[Union[aws_service.CreateAwsClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + aws_cluster: Optional[aws_resources.AwsCluster] = None, + aws_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource + on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_create_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + aws_cluster = gke_multicloud_v1.AwsCluster() + aws_cluster.networking.vpc_id = "vpc_id_value" + aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + aws_cluster.aws_region = "aws_region_value" + aws_cluster.control_plane.version = "version_value" + aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] + aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" + aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" + aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAwsClusterRequest( + parent="parent_value", + aws_cluster=aws_cluster, + aws_cluster_id="aws_cluster_id_value", + ) + + # Make the request + operation = client.create_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.CreateAwsClusterRequest, dict]): + The request object. Request message for ``AwsClusters.CreateAwsCluster`` + method. + parent (str): + Required. The parent location where this + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + aws_cluster (google.cloud.gke_multicloud_v1.types.AwsCluster): + Required. The specification of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + to create. + + This corresponds to the ``aws_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + aws_cluster_id (str): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource name formatted as + ``projects//locations//awsClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``aws_cluster_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AwsCluster` + An Anthos cluster running on AWS. + + """ + # 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, aws_cluster, aws_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.CreateAwsClusterRequest): + request = aws_service.CreateAwsClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if aws_cluster is not None: + request.aws_cluster = aws_cluster + if aws_cluster_id is not None: + request.aws_cluster_id = aws_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_aws_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + aws_resources.AwsCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_aws_cluster(self, + request: Optional[Union[aws_service.UpdateAwsClusterRequest, dict]] = None, + *, + aws_cluster: Optional[aws_resources.AwsCluster] = 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, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates an + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + .. 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 gke_multicloud_v1 + + def sample_update_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + aws_cluster = gke_multicloud_v1.AwsCluster() + aws_cluster.networking.vpc_id = "vpc_id_value" + aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + aws_cluster.aws_region = "aws_region_value" + aws_cluster.control_plane.version = "version_value" + aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] + aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" + aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" + aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAwsClusterRequest( + aws_cluster=aws_cluster, + ) + + # Make the request + operation = client.update_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.UpdateAwsClusterRequest, dict]): + The request object. Request message for ``AwsClusters.UpdateAwsCluster`` + method. + aws_cluster (google.cloud.gke_multicloud_v1.types.AwsCluster): + Required. The + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource to update. + + This corresponds to the ``aws_cluster`` 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 path + must be supplied in this field. The elements of the + repeated paths field can only include these fields from + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]: + + - ``description``. + - ``annotations``. + - ``control_plane.version``. + - ``authorization.admin_users``. + - ``authorization.admin_groups``. + - ``binary_authorization.evaluation_mode``. + - ``control_plane.aws_services_authentication.role_arn``. + - ``control_plane.aws_services_authentication.role_session_name``. + - ``control_plane.config_encryption.kms_key_arn``. + - ``control_plane.instance_type``. + - ``control_plane.security_group_ids``. + - ``control_plane.proxy_config``. + - ``control_plane.proxy_config.secret_arn``. + - ``control_plane.proxy_config.secret_version``. + - ``control_plane.root_volume.size_gib``. + - ``control_plane.root_volume.volume_type``. + - ``control_plane.root_volume.iops``. + - ``control_plane.root_volume.throughput``. + - ``control_plane.root_volume.kms_key_arn``. + - ``control_plane.ssh_config``. + - ``control_plane.ssh_config.ec2_key_pair``. + - ``control_plane.instance_placement.tenancy``. + - ``control_plane.iam_instance_profile``. + - ``logging_config.component_config.enable_components``. + - ``control_plane.tags``. + - ``monitoring_config.managed_prometheus_config.enabled``. + - ``networking.per_node_pool_sg_rules_disabled``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AwsCluster` + An Anthos cluster running on AWS. + + """ + # 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([aws_cluster, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.UpdateAwsClusterRequest): + request = aws_service.UpdateAwsClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if aws_cluster is not None: + request.aws_cluster = aws_cluster + 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_aws_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_cluster.name", request.aws_cluster.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + aws_resources.AwsCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_aws_cluster(self, + request: Optional[Union[aws_service.GetAwsClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_resources.AwsCluster: + r"""Describes a specific + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] 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 gke_multicloud_v1 + + def sample_get_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_aws_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAwsClusterRequest, dict]): + The request object. Request message for ``AwsClusters.GetAwsCluster`` + method. + name (str): + Required. The name of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource to describe. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AwsCluster: + An Anthos cluster running on AWS. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GetAwsClusterRequest): + request = aws_service.GetAwsClusterRequest(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_aws_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_aws_clusters(self, + request: Optional[Union[aws_service.ListAwsClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAwsClustersPager: + r"""Lists all [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resources on a given Google Cloud project and region. + + .. 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 gke_multicloud_v1 + + def sample_list_aws_clusters(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAwsClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_aws_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest, dict]): + The request object. Request message for ``AwsClusters.ListAwsClusters`` + method. + parent (str): + Required. The parent location which owns this collection + of + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsClustersPager: + Response message for AwsClusters.ListAwsClusters method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.ListAwsClustersRequest): + request = aws_service.ListAwsClustersRequest(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_aws_clusters] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAwsClustersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_aws_cluster(self, + request: Optional[Union[aws_service.DeleteAwsClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a specific + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. + + Fails if the cluster has one or more associated + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_delete_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAwsClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.DeleteAwsClusterRequest, dict]): + The request object. Request message for ``AwsClusters.DeleteAwsCluster`` + method. + name (str): + Required. The resource name the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + to delete. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.DeleteAwsClusterRequest): + request = aws_service.DeleteAwsClusterRequest(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_aws_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_aws_cluster_agent_token(self, + request: Optional[Union[aws_service.GenerateAwsClusterAgentTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_service.GenerateAwsClusterAgentTokenResponse: + r"""Generates an access token for a cluster agent. + + .. 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 gke_multicloud_v1 + + def sample_generate_aws_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAwsClusterAgentTokenRequest( + aws_cluster="aws_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = client.generate_aws_cluster_agent_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenRequest, dict]): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenResponse: + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GenerateAwsClusterAgentTokenRequest): + request = aws_service.GenerateAwsClusterAgentTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_aws_cluster_agent_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_cluster", request.aws_cluster), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_aws_access_token(self, + request: Optional[Union[aws_service.GenerateAwsAccessTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_service.GenerateAwsAccessTokenResponse: + r"""Generates a short-lived access token to authenticate to a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] 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 gke_multicloud_v1 + + def sample_generate_aws_access_token(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAwsAccessTokenRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = client.generate_aws_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenRequest, dict]): + The request object. Request message for + ``AwsClusters.GenerateAwsAccessToken`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenResponse: + Response message for AwsClusters.GenerateAwsAccessToken + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GenerateAwsAccessTokenRequest): + request = aws_service.GenerateAwsAccessTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_aws_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_cluster", request.aws_cluster), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_aws_node_pool(self, + request: Optional[Union[aws_service.CreateAwsNodePoolRequest, dict]] = None, + *, + parent: Optional[str] = None, + aws_node_pool: Optional[aws_resources.AwsNodePool] = None, + aws_node_pool_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool], + attached to a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_create_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + aws_node_pool = gke_multicloud_v1.AwsNodePool() + aws_node_pool.version = "version_value" + aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" + aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_node_pool.autoscaling.min_node_count = 1489 + aws_node_pool.autoscaling.max_node_count = 1491 + aws_node_pool.subnet_id = "subnet_id_value" + aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.CreateAwsNodePoolRequest( + parent="parent_value", + aws_node_pool=aws_node_pool, + aws_node_pool_id="aws_node_pool_id_value", + ) + + # Make the request + operation = client.create_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.CreateAwsNodePoolRequest, dict]): + The request object. Response message for ``AwsClusters.CreateAwsNodePool`` + method. + parent (str): + Required. The + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource where this node pool will be created. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + aws_node_pool (google.cloud.gke_multicloud_v1.types.AwsNodePool): + Required. The specification of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + to create. + + This corresponds to the ``aws_node_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + aws_node_pool_id (str): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource name formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``aws_node_pool_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AwsNodePool` + An Anthos node pool running on AWS. + + """ + # 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, aws_node_pool, aws_node_pool_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.CreateAwsNodePoolRequest): + request = aws_service.CreateAwsNodePoolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if aws_node_pool is not None: + request.aws_node_pool = aws_node_pool + if aws_node_pool_id is not None: + request.aws_node_pool_id = aws_node_pool_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_aws_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + aws_resources.AwsNodePool, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_aws_node_pool(self, + request: Optional[Union[aws_service.UpdateAwsNodePoolRequest, dict]] = None, + *, + aws_node_pool: Optional[aws_resources.AwsNodePool] = 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, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates an + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. + + .. 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 gke_multicloud_v1 + + def sample_update_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + aws_node_pool = gke_multicloud_v1.AwsNodePool() + aws_node_pool.version = "version_value" + aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" + aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_node_pool.autoscaling.min_node_count = 1489 + aws_node_pool.autoscaling.max_node_count = 1491 + aws_node_pool.subnet_id = "subnet_id_value" + aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.UpdateAwsNodePoolRequest( + aws_node_pool=aws_node_pool, + ) + + # Make the request + operation = client.update_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.UpdateAwsNodePoolRequest, dict]): + The request object. Request message for ``AwsClusters.UpdateAwsNodePool`` + method. + aws_node_pool (google.cloud.gke_multicloud_v1.types.AwsNodePool): + Required. The + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource to update. + + This corresponds to the ``aws_node_pool`` 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 path + must be supplied in this field. The elements of the + repeated paths field can only include these fields from + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]: + + - ``annotations``. + - ``version``. + - ``autoscaling.min_node_count``. + - ``autoscaling.max_node_count``. + - ``config.config_encryption.kms_key_arn``. + - ``config.security_group_ids``. + - ``config.root_volume.iops``. + - ``config.root_volume.throughput``. + - ``config.root_volume.kms_key_arn``. + - ``config.root_volume.volume_type``. + - ``config.root_volume.size_gib``. + - ``config.proxy_config``. + - ``config.proxy_config.secret_arn``. + - ``config.proxy_config.secret_version``. + - ``config.ssh_config``. + - ``config.ssh_config.ec2_key_pair``. + - ``config.instance_placement.tenancy``. + - ``config.iam_instance_profile``. + - ``config.labels``. + - ``config.tags``. + - ``config.autoscaling_metrics_collection``. + - ``config.autoscaling_metrics_collection.granularity``. + - ``config.autoscaling_metrics_collection.metrics``. + - ``config.instance_type``. + - ``management.auto_repair``. + - ``management``. + - ``update_settings``. + - ``update_settings.surge_settings``. + - ``update_settings.surge_settings.max_surge``. + - ``update_settings.surge_settings.max_unavailable``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AwsNodePool` + An Anthos node pool running on AWS. + + """ + # 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([aws_node_pool, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.UpdateAwsNodePoolRequest): + request = aws_service.UpdateAwsNodePoolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if aws_node_pool is not None: + request.aws_node_pool = aws_node_pool + 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_aws_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_node_pool.name", request.aws_node_pool.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + aws_resources.AwsNodePool, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def rollback_aws_node_pool_update(self, + request: Optional[Union[aws_service.RollbackAwsNodePoolUpdateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Rolls back a previously aborted or failed + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] update + request. Makes no changes if the last update request + successfully finished. If an update request is in progress, you + cannot rollback the update. You must first cancel or let it + finish unsuccessfully before you can rollback. + + .. 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 gke_multicloud_v1 + + def sample_rollback_aws_node_pool_update(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.RollbackAwsNodePoolUpdateRequest( + name="name_value", + ) + + # Make the request + operation = client.rollback_aws_node_pool_update(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.RollbackAwsNodePoolUpdateRequest, dict]): + The request object. Request message for + ``AwsClusters.RollbackAwsNodePoolUpdate`` method. + name (str): + Required. The name of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource to rollback. + + ``AwsNodePool`` names are formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AwsNodePool` + An Anthos node pool running on AWS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.RollbackAwsNodePoolUpdateRequest): + request = aws_service.RollbackAwsNodePoolUpdateRequest(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.rollback_aws_node_pool_update] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + aws_resources.AwsNodePool, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_aws_node_pool(self, + request: Optional[Union[aws_service.GetAwsNodePoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_resources.AwsNodePool: + r"""Describes a specific + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + 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 gke_multicloud_v1 + + def sample_get_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsNodePoolRequest( + name="name_value", + ) + + # Make the request + response = client.get_aws_node_pool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAwsNodePoolRequest, dict]): + The request object. Request message for ``AwsClusters.GetAwsNodePool`` + method. + name (str): + Required. The name of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource to describe. + + ``AwsNodePool`` names are formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AwsNodePool: + An Anthos node pool running on AWS. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GetAwsNodePoolRequest): + request = aws_service.GetAwsNodePoolRequest(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_aws_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_aws_node_pools(self, + request: Optional[Union[aws_service.ListAwsNodePoolsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAwsNodePoolsPager: + r"""Lists all + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources on a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + .. 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 gke_multicloud_v1 + + def sample_list_aws_node_pools(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAwsNodePoolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_aws_node_pools(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest, dict]): + The request object. Request message for ``AwsClusters.ListAwsNodePools`` + method. + parent (str): + Required. The parent ``AwsCluster`` which owns this + collection of + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsNodePoolsPager: + Response message for AwsClusters.ListAwsNodePools + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.ListAwsNodePoolsRequest): + request = aws_service.ListAwsNodePoolsRequest(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_aws_node_pools] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAwsNodePoolsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_aws_node_pool(self, + request: Optional[Union[aws_service.DeleteAwsNodePoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a specific + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_delete_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAwsNodePoolRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.DeleteAwsNodePoolRequest, dict]): + The request object. Request message for ``AwsClusters.DeleteAwsNodePool`` + method. + name (str): + Required. The resource name the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + to delete. + + ``AwsNodePool`` names are formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.DeleteAwsNodePoolRequest): + request = aws_service.DeleteAwsNodePoolRequest(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_aws_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_aws_open_id_config(self, + request: Optional[Union[aws_service.GetAwsOpenIdConfigRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_resources.AwsOpenIdConfig: + r"""Gets the OIDC discovery document for the cluster. See the + `OpenID Connect Discovery 1.0 + specification `__ + for details. + + .. 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 gke_multicloud_v1 + + def sample_get_aws_open_id_config(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsOpenIdConfigRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = client.get_aws_open_id_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAwsOpenIdConfigRequest, dict]): + The request object. GetAwsOpenIdConfigRequest gets the + OIDC discovery document for the cluster. + See the OpenID Connect Discovery 1.0 + specification for details. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AwsOpenIdConfig: + AwsOpenIdConfig is an OIDC discovery + document for the cluster. See the OpenID + Connect Discovery 1.0 specification for + details. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GetAwsOpenIdConfigRequest): + request = aws_service.GetAwsOpenIdConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_aws_open_id_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_cluster", request.aws_cluster), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_aws_json_web_keys(self, + request: Optional[Union[aws_service.GetAwsJsonWebKeysRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_resources.AwsJsonWebKeys: + r"""Gets the public component of the cluster signing keys + in JSON Web Key format. + + .. 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 gke_multicloud_v1 + + def sample_get_aws_json_web_keys(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsJsonWebKeysRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = client.get_aws_json_web_keys(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAwsJsonWebKeysRequest, dict]): + The request object. GetAwsJsonWebKeysRequest gets the public component of + the keys used by the cluster to sign token requests. + This will be the jwks_uri for the discover document + returned by getOpenIDConfig. See the OpenID Connect + Discovery 1.0 specification for details. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AwsJsonWebKeys: + AwsJsonWebKeys is a valid JSON Web + Key Set as specififed in RFC 7517. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GetAwsJsonWebKeysRequest): + request = aws_service.GetAwsJsonWebKeysRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_aws_json_web_keys] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("aws_cluster", request.aws_cluster), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_aws_server_config(self, + request: Optional[Union[aws_service.GetAwsServerConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> aws_resources.AwsServerConfig: + r"""Returns information, such as supported AWS regions + and Kubernetes versions, on a given Google Cloud + 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 gke_multicloud_v1 + + def sample_get_aws_server_config(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsServerConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_aws_server_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAwsServerConfigRequest, dict]): + The request object. GetAwsServerConfigRequest gets the + server config of GKE cluster on AWS. + name (str): + Required. The name of the + [AwsServerConfig][google.cloud.gkemulticloud.v1.AwsServerConfig] + resource to describe. + + ``AwsServerConfig`` names are formatted as + ``projects//locations//awsServerConfig``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AwsServerConfig: + AwsServerConfig is the configuration + of GKE cluster on AWS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, aws_service.GetAwsServerConfigRequest): + request = aws_service.GetAwsServerConfigRequest(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_aws_server_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AwsClustersClient": + 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, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def 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, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + 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, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AwsClustersClient", +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/pagers.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/pagers.py new file mode 100644 index 000000000000..37c279974e69 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/pagers.py @@ -0,0 +1,306 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.gke_multicloud_v1.types import aws_resources +from google.cloud.gke_multicloud_v1.types import aws_service + + +class ListAwsClustersPager: + """A pager for iterating through ``list_aws_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``aws_clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAwsClusters`` requests and continue to iterate + through the ``aws_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse` + 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[..., aws_service.ListAwsClustersResponse], + request: aws_service.ListAwsClustersRequest, + response: aws_service.ListAwsClustersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = aws_service.ListAwsClustersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[aws_service.ListAwsClustersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[aws_resources.AwsCluster]: + for page in self.pages: + yield from page.aws_clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAwsClustersAsyncPager: + """A pager for iterating through ``list_aws_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``aws_clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAwsClusters`` requests and continue to iterate + through the ``aws_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse` + 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[aws_service.ListAwsClustersResponse]], + request: aws_service.ListAwsClustersRequest, + response: aws_service.ListAwsClustersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = aws_service.ListAwsClustersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[aws_service.ListAwsClustersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[aws_resources.AwsCluster]: + async def async_generator(): + async for page in self.pages: + for response in page.aws_clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAwsNodePoolsPager: + """A pager for iterating through ``list_aws_node_pools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``aws_node_pools`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAwsNodePools`` requests and continue to iterate + through the ``aws_node_pools`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse` + 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[..., aws_service.ListAwsNodePoolsResponse], + request: aws_service.ListAwsNodePoolsRequest, + response: aws_service.ListAwsNodePoolsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = aws_service.ListAwsNodePoolsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[aws_service.ListAwsNodePoolsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[aws_resources.AwsNodePool]: + for page in self.pages: + yield from page.aws_node_pools + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAwsNodePoolsAsyncPager: + """A pager for iterating through ``list_aws_node_pools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``aws_node_pools`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAwsNodePools`` requests and continue to iterate + through the ``aws_node_pools`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse` + 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[aws_service.ListAwsNodePoolsResponse]], + request: aws_service.ListAwsNodePoolsRequest, + response: aws_service.ListAwsNodePoolsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = aws_service.ListAwsNodePoolsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[aws_service.ListAwsNodePoolsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[aws_resources.AwsNodePool]: + async def async_generator(): + async for page in self.pages: + for response in page.aws_node_pools: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/README.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/README.rst new file mode 100644 index 000000000000..9e0624faad5d --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AwsClustersTransport` is the ABC for all transports. +- public child `AwsClustersGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AwsClustersGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAwsClustersRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AwsClustersRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/__init__.py new file mode 100644 index 000000000000..f9cb58b758a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AwsClustersTransport +from .grpc import AwsClustersGrpcTransport +from .grpc_asyncio import AwsClustersGrpcAsyncIOTransport +from .rest import AwsClustersRestTransport +from .rest import AwsClustersRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AwsClustersTransport]] +_transport_registry['grpc'] = AwsClustersGrpcTransport +_transport_registry['grpc_asyncio'] = AwsClustersGrpcAsyncIOTransport +_transport_registry['rest'] = AwsClustersRestTransport + +__all__ = ( + 'AwsClustersTransport', + 'AwsClustersGrpcTransport', + 'AwsClustersGrpcAsyncIOTransport', + 'AwsClustersRestTransport', + 'AwsClustersRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/base.py new file mode 100644 index 000000000000..0497798ba75e --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/base.py @@ -0,0 +1,509 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.gke_multicloud_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.gke_multicloud_v1.types import aws_resources +from google.cloud.gke_multicloud_v1.types import aws_service +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AwsClustersTransport(abc.ABC): + """Abstract transport class for AwsClusters.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'gkemulticloud.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_aws_cluster: gapic_v1.method.wrap_method( + self.create_aws_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_aws_cluster: gapic_v1.method.wrap_method( + self.update_aws_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_aws_cluster: gapic_v1.method.wrap_method( + self.get_aws_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_aws_clusters: gapic_v1.method.wrap_method( + self.list_aws_clusters, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_aws_cluster: gapic_v1.method.wrap_method( + self.delete_aws_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.generate_aws_cluster_agent_token: gapic_v1.method.wrap_method( + self.generate_aws_cluster_agent_token, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_aws_access_token: gapic_v1.method.wrap_method( + self.generate_aws_access_token, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_aws_node_pool: gapic_v1.method.wrap_method( + self.create_aws_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.update_aws_node_pool: gapic_v1.method.wrap_method( + self.update_aws_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.rollback_aws_node_pool_update: gapic_v1.method.wrap_method( + self.rollback_aws_node_pool_update, + default_timeout=60.0, + client_info=client_info, + ), + self.get_aws_node_pool: gapic_v1.method.wrap_method( + self.get_aws_node_pool, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_aws_node_pools: gapic_v1.method.wrap_method( + self.list_aws_node_pools, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_aws_node_pool: gapic_v1.method.wrap_method( + self.delete_aws_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.get_aws_open_id_config: gapic_v1.method.wrap_method( + self.get_aws_open_id_config, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_aws_json_web_keys: gapic_v1.method.wrap_method( + self.get_aws_json_web_keys, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_aws_server_config: gapic_v1.method.wrap_method( + self.get_aws_server_config, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + 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 create_aws_cluster(self) -> Callable[ + [aws_service.CreateAwsClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_aws_cluster(self) -> Callable[ + [aws_service.UpdateAwsClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_aws_cluster(self) -> Callable[ + [aws_service.GetAwsClusterRequest], + Union[ + aws_resources.AwsCluster, + Awaitable[aws_resources.AwsCluster] + ]]: + raise NotImplementedError() + + @property + def list_aws_clusters(self) -> Callable[ + [aws_service.ListAwsClustersRequest], + Union[ + aws_service.ListAwsClustersResponse, + Awaitable[aws_service.ListAwsClustersResponse] + ]]: + raise NotImplementedError() + + @property + def delete_aws_cluster(self) -> Callable[ + [aws_service.DeleteAwsClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_aws_cluster_agent_token(self) -> Callable[ + [aws_service.GenerateAwsClusterAgentTokenRequest], + Union[ + aws_service.GenerateAwsClusterAgentTokenResponse, + Awaitable[aws_service.GenerateAwsClusterAgentTokenResponse] + ]]: + raise NotImplementedError() + + @property + def generate_aws_access_token(self) -> Callable[ + [aws_service.GenerateAwsAccessTokenRequest], + Union[ + aws_service.GenerateAwsAccessTokenResponse, + Awaitable[aws_service.GenerateAwsAccessTokenResponse] + ]]: + raise NotImplementedError() + + @property + def create_aws_node_pool(self) -> Callable[ + [aws_service.CreateAwsNodePoolRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_aws_node_pool(self) -> Callable[ + [aws_service.UpdateAwsNodePoolRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def rollback_aws_node_pool_update(self) -> Callable[ + [aws_service.RollbackAwsNodePoolUpdateRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_aws_node_pool(self) -> Callable[ + [aws_service.GetAwsNodePoolRequest], + Union[ + aws_resources.AwsNodePool, + Awaitable[aws_resources.AwsNodePool] + ]]: + raise NotImplementedError() + + @property + def list_aws_node_pools(self) -> Callable[ + [aws_service.ListAwsNodePoolsRequest], + Union[ + aws_service.ListAwsNodePoolsResponse, + Awaitable[aws_service.ListAwsNodePoolsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_aws_node_pool(self) -> Callable[ + [aws_service.DeleteAwsNodePoolRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_aws_open_id_config(self) -> Callable[ + [aws_service.GetAwsOpenIdConfigRequest], + Union[ + aws_resources.AwsOpenIdConfig, + Awaitable[aws_resources.AwsOpenIdConfig] + ]]: + raise NotImplementedError() + + @property + def get_aws_json_web_keys(self) -> Callable[ + [aws_service.GetAwsJsonWebKeysRequest], + Union[ + aws_resources.AwsJsonWebKeys, + Awaitable[aws_resources.AwsJsonWebKeys] + ]]: + raise NotImplementedError() + + @property + def get_aws_server_config(self) -> Callable[ + [aws_service.GetAwsServerConfigRequest], + Union[ + aws_resources.AwsServerConfig, + Awaitable[aws_resources.AwsServerConfig] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AwsClustersTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc.py new file mode 100644 index 000000000000..f21051643280 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc.py @@ -0,0 +1,881 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +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 +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.gke_multicloud_v1.types import aws_resources +from google.cloud.gke_multicloud_v1.types import aws_service +from google.longrunning import operations_pb2 # type: ignore +from .base import AwsClustersTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AwsClustersGrpcTransport(AwsClustersTransport): + """gRPC backend transport for AwsClusters. + + The AwsClusters API provides a single centrally managed + service to create and manage Anthos clusters that run on AWS + infrastructure. + + 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 = 'gkemulticloud.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'gkemulticloud.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._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_aws_cluster(self) -> Callable[ + [aws_service.CreateAwsClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create aws cluster method over gRPC. + + Creates a new + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource + on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAwsClusterRequest], + ~.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_aws_cluster' not in self._stubs: + self._stubs['create_aws_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsCluster', + request_serializer=aws_service.CreateAwsClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_aws_cluster'] + + @property + def update_aws_cluster(self) -> Callable[ + [aws_service.UpdateAwsClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update aws cluster method over gRPC. + + Updates an + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + Returns: + Callable[[~.UpdateAwsClusterRequest], + ~.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_aws_cluster' not in self._stubs: + self._stubs['update_aws_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/UpdateAwsCluster', + request_serializer=aws_service.UpdateAwsClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_aws_cluster'] + + @property + def get_aws_cluster(self) -> Callable[ + [aws_service.GetAwsClusterRequest], + aws_resources.AwsCluster]: + r"""Return a callable for the get aws cluster method over gRPC. + + Describes a specific + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. + + Returns: + Callable[[~.GetAwsClusterRequest], + ~.AwsCluster]: + 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_aws_cluster' not in self._stubs: + self._stubs['get_aws_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsCluster', + request_serializer=aws_service.GetAwsClusterRequest.serialize, + response_deserializer=aws_resources.AwsCluster.deserialize, + ) + return self._stubs['get_aws_cluster'] + + @property + def list_aws_clusters(self) -> Callable[ + [aws_service.ListAwsClustersRequest], + aws_service.ListAwsClustersResponse]: + r"""Return a callable for the list aws clusters method over gRPC. + + Lists all [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resources on a given Google Cloud project and region. + + Returns: + Callable[[~.ListAwsClustersRequest], + ~.ListAwsClustersResponse]: + 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_aws_clusters' not in self._stubs: + self._stubs['list_aws_clusters'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/ListAwsClusters', + request_serializer=aws_service.ListAwsClustersRequest.serialize, + response_deserializer=aws_service.ListAwsClustersResponse.deserialize, + ) + return self._stubs['list_aws_clusters'] + + @property + def delete_aws_cluster(self) -> Callable[ + [aws_service.DeleteAwsClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete aws cluster method over gRPC. + + Deletes a specific + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. + + Fails if the cluster has one or more associated + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAwsClusterRequest], + ~.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_aws_cluster' not in self._stubs: + self._stubs['delete_aws_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/DeleteAwsCluster', + request_serializer=aws_service.DeleteAwsClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_aws_cluster'] + + @property + def generate_aws_cluster_agent_token(self) -> Callable[ + [aws_service.GenerateAwsClusterAgentTokenRequest], + aws_service.GenerateAwsClusterAgentTokenResponse]: + r"""Return a callable for the generate aws cluster agent + token method over gRPC. + + Generates an access token for a cluster agent. + + Returns: + Callable[[~.GenerateAwsClusterAgentTokenRequest], + ~.GenerateAwsClusterAgentTokenResponse]: + 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_aws_cluster_agent_token' not in self._stubs: + self._stubs['generate_aws_cluster_agent_token'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GenerateAwsClusterAgentToken', + request_serializer=aws_service.GenerateAwsClusterAgentTokenRequest.serialize, + response_deserializer=aws_service.GenerateAwsClusterAgentTokenResponse.deserialize, + ) + return self._stubs['generate_aws_cluster_agent_token'] + + @property + def generate_aws_access_token(self) -> Callable[ + [aws_service.GenerateAwsAccessTokenRequest], + aws_service.GenerateAwsAccessTokenResponse]: + r"""Return a callable for the generate aws access token method over gRPC. + + Generates a short-lived access token to authenticate to a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. + + Returns: + Callable[[~.GenerateAwsAccessTokenRequest], + ~.GenerateAwsAccessTokenResponse]: + 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_aws_access_token' not in self._stubs: + self._stubs['generate_aws_access_token'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GenerateAwsAccessToken', + request_serializer=aws_service.GenerateAwsAccessTokenRequest.serialize, + response_deserializer=aws_service.GenerateAwsAccessTokenResponse.deserialize, + ) + return self._stubs['generate_aws_access_token'] + + @property + def create_aws_node_pool(self) -> Callable[ + [aws_service.CreateAwsNodePoolRequest], + operations_pb2.Operation]: + r"""Return a callable for the create aws node pool method over gRPC. + + Creates a new + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool], + attached to a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAwsNodePoolRequest], + ~.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_aws_node_pool' not in self._stubs: + self._stubs['create_aws_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsNodePool', + request_serializer=aws_service.CreateAwsNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_aws_node_pool'] + + @property + def update_aws_node_pool(self) -> Callable[ + [aws_service.UpdateAwsNodePoolRequest], + operations_pb2.Operation]: + r"""Return a callable for the update aws node pool method over gRPC. + + Updates an + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. + + Returns: + Callable[[~.UpdateAwsNodePoolRequest], + ~.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_aws_node_pool' not in self._stubs: + self._stubs['update_aws_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/UpdateAwsNodePool', + request_serializer=aws_service.UpdateAwsNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_aws_node_pool'] + + @property + def rollback_aws_node_pool_update(self) -> Callable[ + [aws_service.RollbackAwsNodePoolUpdateRequest], + operations_pb2.Operation]: + r"""Return a callable for the rollback aws node pool update method over gRPC. + + Rolls back a previously aborted or failed + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] update + request. Makes no changes if the last update request + successfully finished. If an update request is in progress, you + cannot rollback the update. You must first cancel or let it + finish unsuccessfully before you can rollback. + + Returns: + Callable[[~.RollbackAwsNodePoolUpdateRequest], + ~.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 'rollback_aws_node_pool_update' not in self._stubs: + self._stubs['rollback_aws_node_pool_update'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/RollbackAwsNodePoolUpdate', + request_serializer=aws_service.RollbackAwsNodePoolUpdateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rollback_aws_node_pool_update'] + + @property + def get_aws_node_pool(self) -> Callable[ + [aws_service.GetAwsNodePoolRequest], + aws_resources.AwsNodePool]: + r"""Return a callable for the get aws node pool method over gRPC. + + Describes a specific + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource. + + Returns: + Callable[[~.GetAwsNodePoolRequest], + ~.AwsNodePool]: + 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_aws_node_pool' not in self._stubs: + self._stubs['get_aws_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsNodePool', + request_serializer=aws_service.GetAwsNodePoolRequest.serialize, + response_deserializer=aws_resources.AwsNodePool.deserialize, + ) + return self._stubs['get_aws_node_pool'] + + @property + def list_aws_node_pools(self) -> Callable[ + [aws_service.ListAwsNodePoolsRequest], + aws_service.ListAwsNodePoolsResponse]: + r"""Return a callable for the list aws node pools method over gRPC. + + Lists all + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources on a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + Returns: + Callable[[~.ListAwsNodePoolsRequest], + ~.ListAwsNodePoolsResponse]: + 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_aws_node_pools' not in self._stubs: + self._stubs['list_aws_node_pools'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/ListAwsNodePools', + request_serializer=aws_service.ListAwsNodePoolsRequest.serialize, + response_deserializer=aws_service.ListAwsNodePoolsResponse.deserialize, + ) + return self._stubs['list_aws_node_pools'] + + @property + def delete_aws_node_pool(self) -> Callable[ + [aws_service.DeleteAwsNodePoolRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete aws node pool method over gRPC. + + Deletes a specific + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAwsNodePoolRequest], + ~.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_aws_node_pool' not in self._stubs: + self._stubs['delete_aws_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/DeleteAwsNodePool', + request_serializer=aws_service.DeleteAwsNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_aws_node_pool'] + + @property + def get_aws_open_id_config(self) -> Callable[ + [aws_service.GetAwsOpenIdConfigRequest], + aws_resources.AwsOpenIdConfig]: + r"""Return a callable for the get aws open id config method over gRPC. + + Gets the OIDC discovery document for the cluster. See the + `OpenID Connect Discovery 1.0 + specification `__ + for details. + + Returns: + Callable[[~.GetAwsOpenIdConfigRequest], + ~.AwsOpenIdConfig]: + 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_aws_open_id_config' not in self._stubs: + self._stubs['get_aws_open_id_config'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsOpenIdConfig', + request_serializer=aws_service.GetAwsOpenIdConfigRequest.serialize, + response_deserializer=aws_resources.AwsOpenIdConfig.deserialize, + ) + return self._stubs['get_aws_open_id_config'] + + @property + def get_aws_json_web_keys(self) -> Callable[ + [aws_service.GetAwsJsonWebKeysRequest], + aws_resources.AwsJsonWebKeys]: + r"""Return a callable for the get aws json web keys method over gRPC. + + Gets the public component of the cluster signing keys + in JSON Web Key format. + + Returns: + Callable[[~.GetAwsJsonWebKeysRequest], + ~.AwsJsonWebKeys]: + 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_aws_json_web_keys' not in self._stubs: + self._stubs['get_aws_json_web_keys'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsJsonWebKeys', + request_serializer=aws_service.GetAwsJsonWebKeysRequest.serialize, + response_deserializer=aws_resources.AwsJsonWebKeys.deserialize, + ) + return self._stubs['get_aws_json_web_keys'] + + @property + def get_aws_server_config(self) -> Callable[ + [aws_service.GetAwsServerConfigRequest], + aws_resources.AwsServerConfig]: + r"""Return a callable for the get aws server config method over gRPC. + + Returns information, such as supported AWS regions + and Kubernetes versions, on a given Google Cloud + location. + + Returns: + Callable[[~.GetAwsServerConfigRequest], + ~.AwsServerConfig]: + 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_aws_server_config' not in self._stubs: + self._stubs['get_aws_server_config'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsServerConfig', + request_serializer=aws_service.GetAwsServerConfigRequest.serialize, + response_deserializer=aws_resources.AwsServerConfig.deserialize, + ) + return self._stubs['get_aws_server_config'] + + def close(self): + self._logged_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._logged_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._logged_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._logged_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._logged_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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AwsClustersGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc_asyncio.py new file mode 100644 index 000000000000..16709655e9e5 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc_asyncio.py @@ -0,0 +1,1077 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.gke_multicloud_v1.types import aws_resources +from google.cloud.gke_multicloud_v1.types import aws_service +from google.longrunning import operations_pb2 # type: ignore +from .base import AwsClustersTransport, DEFAULT_CLIENT_INFO +from .grpc import AwsClustersGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AwsClustersGrpcAsyncIOTransport(AwsClustersTransport): + """gRPC AsyncIO backend transport for AwsClusters. + + The AwsClusters API provides a single centrally managed + service to create and manage Anthos clusters that run on AWS + infrastructure. + + 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 = 'gkemulticloud.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'gkemulticloud.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_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._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_aws_cluster(self) -> Callable[ + [aws_service.CreateAwsClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create aws cluster method over gRPC. + + Creates a new + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource + on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAwsClusterRequest], + 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_aws_cluster' not in self._stubs: + self._stubs['create_aws_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsCluster', + request_serializer=aws_service.CreateAwsClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_aws_cluster'] + + @property + def update_aws_cluster(self) -> Callable[ + [aws_service.UpdateAwsClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update aws cluster method over gRPC. + + Updates an + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + Returns: + Callable[[~.UpdateAwsClusterRequest], + 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_aws_cluster' not in self._stubs: + self._stubs['update_aws_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/UpdateAwsCluster', + request_serializer=aws_service.UpdateAwsClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_aws_cluster'] + + @property + def get_aws_cluster(self) -> Callable[ + [aws_service.GetAwsClusterRequest], + Awaitable[aws_resources.AwsCluster]]: + r"""Return a callable for the get aws cluster method over gRPC. + + Describes a specific + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. + + Returns: + Callable[[~.GetAwsClusterRequest], + Awaitable[~.AwsCluster]]: + 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_aws_cluster' not in self._stubs: + self._stubs['get_aws_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsCluster', + request_serializer=aws_service.GetAwsClusterRequest.serialize, + response_deserializer=aws_resources.AwsCluster.deserialize, + ) + return self._stubs['get_aws_cluster'] + + @property + def list_aws_clusters(self) -> Callable[ + [aws_service.ListAwsClustersRequest], + Awaitable[aws_service.ListAwsClustersResponse]]: + r"""Return a callable for the list aws clusters method over gRPC. + + Lists all [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resources on a given Google Cloud project and region. + + Returns: + Callable[[~.ListAwsClustersRequest], + Awaitable[~.ListAwsClustersResponse]]: + 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_aws_clusters' not in self._stubs: + self._stubs['list_aws_clusters'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/ListAwsClusters', + request_serializer=aws_service.ListAwsClustersRequest.serialize, + response_deserializer=aws_service.ListAwsClustersResponse.deserialize, + ) + return self._stubs['list_aws_clusters'] + + @property + def delete_aws_cluster(self) -> Callable[ + [aws_service.DeleteAwsClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete aws cluster method over gRPC. + + Deletes a specific + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. + + Fails if the cluster has one or more associated + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAwsClusterRequest], + 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_aws_cluster' not in self._stubs: + self._stubs['delete_aws_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/DeleteAwsCluster', + request_serializer=aws_service.DeleteAwsClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_aws_cluster'] + + @property + def generate_aws_cluster_agent_token(self) -> Callable[ + [aws_service.GenerateAwsClusterAgentTokenRequest], + Awaitable[aws_service.GenerateAwsClusterAgentTokenResponse]]: + r"""Return a callable for the generate aws cluster agent + token method over gRPC. + + Generates an access token for a cluster agent. + + Returns: + Callable[[~.GenerateAwsClusterAgentTokenRequest], + Awaitable[~.GenerateAwsClusterAgentTokenResponse]]: + 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_aws_cluster_agent_token' not in self._stubs: + self._stubs['generate_aws_cluster_agent_token'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GenerateAwsClusterAgentToken', + request_serializer=aws_service.GenerateAwsClusterAgentTokenRequest.serialize, + response_deserializer=aws_service.GenerateAwsClusterAgentTokenResponse.deserialize, + ) + return self._stubs['generate_aws_cluster_agent_token'] + + @property + def generate_aws_access_token(self) -> Callable[ + [aws_service.GenerateAwsAccessTokenRequest], + Awaitable[aws_service.GenerateAwsAccessTokenResponse]]: + r"""Return a callable for the generate aws access token method over gRPC. + + Generates a short-lived access token to authenticate to a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. + + Returns: + Callable[[~.GenerateAwsAccessTokenRequest], + Awaitable[~.GenerateAwsAccessTokenResponse]]: + 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_aws_access_token' not in self._stubs: + self._stubs['generate_aws_access_token'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GenerateAwsAccessToken', + request_serializer=aws_service.GenerateAwsAccessTokenRequest.serialize, + response_deserializer=aws_service.GenerateAwsAccessTokenResponse.deserialize, + ) + return self._stubs['generate_aws_access_token'] + + @property + def create_aws_node_pool(self) -> Callable[ + [aws_service.CreateAwsNodePoolRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create aws node pool method over gRPC. + + Creates a new + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool], + attached to a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAwsNodePoolRequest], + 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_aws_node_pool' not in self._stubs: + self._stubs['create_aws_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsNodePool', + request_serializer=aws_service.CreateAwsNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_aws_node_pool'] + + @property + def update_aws_node_pool(self) -> Callable[ + [aws_service.UpdateAwsNodePoolRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update aws node pool method over gRPC. + + Updates an + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. + + Returns: + Callable[[~.UpdateAwsNodePoolRequest], + 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_aws_node_pool' not in self._stubs: + self._stubs['update_aws_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/UpdateAwsNodePool', + request_serializer=aws_service.UpdateAwsNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_aws_node_pool'] + + @property + def rollback_aws_node_pool_update(self) -> Callable[ + [aws_service.RollbackAwsNodePoolUpdateRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the rollback aws node pool update method over gRPC. + + Rolls back a previously aborted or failed + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] update + request. Makes no changes if the last update request + successfully finished. If an update request is in progress, you + cannot rollback the update. You must first cancel or let it + finish unsuccessfully before you can rollback. + + Returns: + Callable[[~.RollbackAwsNodePoolUpdateRequest], + 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 'rollback_aws_node_pool_update' not in self._stubs: + self._stubs['rollback_aws_node_pool_update'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/RollbackAwsNodePoolUpdate', + request_serializer=aws_service.RollbackAwsNodePoolUpdateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['rollback_aws_node_pool_update'] + + @property + def get_aws_node_pool(self) -> Callable[ + [aws_service.GetAwsNodePoolRequest], + Awaitable[aws_resources.AwsNodePool]]: + r"""Return a callable for the get aws node pool method over gRPC. + + Describes a specific + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource. + + Returns: + Callable[[~.GetAwsNodePoolRequest], + Awaitable[~.AwsNodePool]]: + 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_aws_node_pool' not in self._stubs: + self._stubs['get_aws_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsNodePool', + request_serializer=aws_service.GetAwsNodePoolRequest.serialize, + response_deserializer=aws_resources.AwsNodePool.deserialize, + ) + return self._stubs['get_aws_node_pool'] + + @property + def list_aws_node_pools(self) -> Callable[ + [aws_service.ListAwsNodePoolsRequest], + Awaitable[aws_service.ListAwsNodePoolsResponse]]: + r"""Return a callable for the list aws node pools method over gRPC. + + Lists all + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources on a given + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + Returns: + Callable[[~.ListAwsNodePoolsRequest], + Awaitable[~.ListAwsNodePoolsResponse]]: + 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_aws_node_pools' not in self._stubs: + self._stubs['list_aws_node_pools'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/ListAwsNodePools', + request_serializer=aws_service.ListAwsNodePoolsRequest.serialize, + response_deserializer=aws_service.ListAwsNodePoolsResponse.deserialize, + ) + return self._stubs['list_aws_node_pools'] + + @property + def delete_aws_node_pool(self) -> Callable[ + [aws_service.DeleteAwsNodePoolRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete aws node pool method over gRPC. + + Deletes a specific + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAwsNodePoolRequest], + 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_aws_node_pool' not in self._stubs: + self._stubs['delete_aws_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/DeleteAwsNodePool', + request_serializer=aws_service.DeleteAwsNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_aws_node_pool'] + + @property + def get_aws_open_id_config(self) -> Callable[ + [aws_service.GetAwsOpenIdConfigRequest], + Awaitable[aws_resources.AwsOpenIdConfig]]: + r"""Return a callable for the get aws open id config method over gRPC. + + Gets the OIDC discovery document for the cluster. See the + `OpenID Connect Discovery 1.0 + specification `__ + for details. + + Returns: + Callable[[~.GetAwsOpenIdConfigRequest], + Awaitable[~.AwsOpenIdConfig]]: + 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_aws_open_id_config' not in self._stubs: + self._stubs['get_aws_open_id_config'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsOpenIdConfig', + request_serializer=aws_service.GetAwsOpenIdConfigRequest.serialize, + response_deserializer=aws_resources.AwsOpenIdConfig.deserialize, + ) + return self._stubs['get_aws_open_id_config'] + + @property + def get_aws_json_web_keys(self) -> Callable[ + [aws_service.GetAwsJsonWebKeysRequest], + Awaitable[aws_resources.AwsJsonWebKeys]]: + r"""Return a callable for the get aws json web keys method over gRPC. + + Gets the public component of the cluster signing keys + in JSON Web Key format. + + Returns: + Callable[[~.GetAwsJsonWebKeysRequest], + Awaitable[~.AwsJsonWebKeys]]: + 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_aws_json_web_keys' not in self._stubs: + self._stubs['get_aws_json_web_keys'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsJsonWebKeys', + request_serializer=aws_service.GetAwsJsonWebKeysRequest.serialize, + response_deserializer=aws_resources.AwsJsonWebKeys.deserialize, + ) + return self._stubs['get_aws_json_web_keys'] + + @property + def get_aws_server_config(self) -> Callable[ + [aws_service.GetAwsServerConfigRequest], + Awaitable[aws_resources.AwsServerConfig]]: + r"""Return a callable for the get aws server config method over gRPC. + + Returns information, such as supported AWS regions + and Kubernetes versions, on a given Google Cloud + location. + + Returns: + Callable[[~.GetAwsServerConfigRequest], + Awaitable[~.AwsServerConfig]]: + 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_aws_server_config' not in self._stubs: + self._stubs['get_aws_server_config'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsServerConfig', + request_serializer=aws_service.GetAwsServerConfigRequest.serialize, + response_deserializer=aws_resources.AwsServerConfig.deserialize, + ) + return self._stubs['get_aws_server_config'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_aws_cluster: self._wrap_method( + self.create_aws_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_aws_cluster: self._wrap_method( + self.update_aws_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_aws_cluster: self._wrap_method( + self.get_aws_cluster, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_aws_clusters: self._wrap_method( + self.list_aws_clusters, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_aws_cluster: self._wrap_method( + self.delete_aws_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.generate_aws_cluster_agent_token: self._wrap_method( + self.generate_aws_cluster_agent_token, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_aws_access_token: self._wrap_method( + self.generate_aws_access_token, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_aws_node_pool: self._wrap_method( + self.create_aws_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.update_aws_node_pool: self._wrap_method( + self.update_aws_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.rollback_aws_node_pool_update: self._wrap_method( + self.rollback_aws_node_pool_update, + default_timeout=60.0, + client_info=client_info, + ), + self.get_aws_node_pool: self._wrap_method( + self.get_aws_node_pool, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_aws_node_pools: self._wrap_method( + self.list_aws_node_pools, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_aws_node_pool: self._wrap_method( + self.delete_aws_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.get_aws_open_id_config: self._wrap_method( + self.get_aws_open_id_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_aws_json_web_keys: self._wrap_method( + self.get_aws_json_web_keys, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_aws_server_config: self._wrap_method( + self.get_aws_server_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @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._logged_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._logged_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._logged_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._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'AwsClustersGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest.py new file mode 100644 index 000000000000..8078628a030f --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest.py @@ -0,0 +1,3204 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # 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 gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.gke_multicloud_v1.types import aws_resources +from google.cloud.gke_multicloud_v1.types import aws_service +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseAwsClustersRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class AwsClustersRestInterceptor: + """Interceptor for AwsClusters. + + 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 AwsClustersRestTransport. + + .. code-block:: python + class MyCustomAwsClustersInterceptor(AwsClustersRestInterceptor): + def pre_create_aws_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_aws_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_aws_node_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_aws_node_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_aws_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_aws_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_aws_node_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_aws_node_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_aws_access_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_aws_access_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_aws_cluster_agent_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_aws_cluster_agent_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_aws_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_aws_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_aws_json_web_keys(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_aws_json_web_keys(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_aws_node_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_aws_node_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_aws_open_id_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_aws_open_id_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_aws_server_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_aws_server_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_aws_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_aws_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_aws_node_pools(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_aws_node_pools(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_rollback_aws_node_pool_update(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_rollback_aws_node_pool_update(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_aws_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_aws_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_aws_node_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_aws_node_pool(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AwsClustersRestTransport(interceptor=MyCustomAwsClustersInterceptor()) + client = AwsClustersClient(transport=transport) + + + """ + def pre_create_aws_cluster(self, request: aws_service.CreateAwsClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.CreateAwsClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_aws_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_create_aws_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_aws_cluster + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_create_aws_node_pool(self, request: aws_service.CreateAwsNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.CreateAwsNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_aws_node_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_create_aws_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_aws_node_pool + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_delete_aws_cluster(self, request: aws_service.DeleteAwsClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.DeleteAwsClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_aws_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_delete_aws_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_aws_cluster + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_delete_aws_node_pool(self, request: aws_service.DeleteAwsNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.DeleteAwsNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_aws_node_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_delete_aws_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_aws_node_pool + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_generate_aws_access_token(self, request: aws_service.GenerateAwsAccessTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GenerateAwsAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for generate_aws_access_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_generate_aws_access_token(self, response: aws_service.GenerateAwsAccessTokenResponse) -> aws_service.GenerateAwsAccessTokenResponse: + """Post-rpc interceptor for generate_aws_access_token + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_generate_aws_cluster_agent_token(self, request: aws_service.GenerateAwsClusterAgentTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GenerateAwsClusterAgentTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for generate_aws_cluster_agent_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_generate_aws_cluster_agent_token(self, response: aws_service.GenerateAwsClusterAgentTokenResponse) -> aws_service.GenerateAwsClusterAgentTokenResponse: + """Post-rpc interceptor for generate_aws_cluster_agent_token + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_get_aws_cluster(self, request: aws_service.GetAwsClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GetAwsClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_aws_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_get_aws_cluster(self, response: aws_resources.AwsCluster) -> aws_resources.AwsCluster: + """Post-rpc interceptor for get_aws_cluster + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_get_aws_json_web_keys(self, request: aws_service.GetAwsJsonWebKeysRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GetAwsJsonWebKeysRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_aws_json_web_keys + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_get_aws_json_web_keys(self, response: aws_resources.AwsJsonWebKeys) -> aws_resources.AwsJsonWebKeys: + """Post-rpc interceptor for get_aws_json_web_keys + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_get_aws_node_pool(self, request: aws_service.GetAwsNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GetAwsNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_aws_node_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_get_aws_node_pool(self, response: aws_resources.AwsNodePool) -> aws_resources.AwsNodePool: + """Post-rpc interceptor for get_aws_node_pool + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_get_aws_open_id_config(self, request: aws_service.GetAwsOpenIdConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GetAwsOpenIdConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_aws_open_id_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_get_aws_open_id_config(self, response: aws_resources.AwsOpenIdConfig) -> aws_resources.AwsOpenIdConfig: + """Post-rpc interceptor for get_aws_open_id_config + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_get_aws_server_config(self, request: aws_service.GetAwsServerConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GetAwsServerConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_aws_server_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_get_aws_server_config(self, response: aws_resources.AwsServerConfig) -> aws_resources.AwsServerConfig: + """Post-rpc interceptor for get_aws_server_config + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_list_aws_clusters(self, request: aws_service.ListAwsClustersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.ListAwsClustersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_aws_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_list_aws_clusters(self, response: aws_service.ListAwsClustersResponse) -> aws_service.ListAwsClustersResponse: + """Post-rpc interceptor for list_aws_clusters + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_list_aws_node_pools(self, request: aws_service.ListAwsNodePoolsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.ListAwsNodePoolsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_aws_node_pools + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_list_aws_node_pools(self, response: aws_service.ListAwsNodePoolsResponse) -> aws_service.ListAwsNodePoolsResponse: + """Post-rpc interceptor for list_aws_node_pools + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_rollback_aws_node_pool_update(self, request: aws_service.RollbackAwsNodePoolUpdateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.RollbackAwsNodePoolUpdateRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for rollback_aws_node_pool_update + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_rollback_aws_node_pool_update(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for rollback_aws_node_pool_update + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_update_aws_cluster(self, request: aws_service.UpdateAwsClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.UpdateAwsClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_aws_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_update_aws_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_aws_cluster + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_update_aws_node_pool(self, request: aws_service.UpdateAwsNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.UpdateAwsNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_aws_node_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters server. + """ + return request, metadata + + def post_update_aws_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_aws_node_pool + + Override in a subclass to manipulate the response + after it is returned by the AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters 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 AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters 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 AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters 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 AwsClusters server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AwsClusters 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 AwsClusters server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AwsClustersRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AwsClustersRestInterceptor + + +class AwsClustersRestTransport(_BaseAwsClustersRestTransport): + """REST backend synchronous transport for AwsClusters. + + The AwsClusters API provides a single centrally managed + service to create and manage Anthos clusters that run on AWS + infrastructure. + + 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 = 'gkemulticloud.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[AwsClustersRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + 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 AwsClustersRestInterceptor() + 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 _CreateAwsCluster(_BaseAwsClustersRestTransport._BaseCreateAwsCluster, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.CreateAwsCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: aws_service.CreateAwsClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create aws cluster method over HTTP. + + Args: + request (~.aws_service.CreateAwsClusterRequest): + The request object. Request message for ``AwsClusters.CreateAwsCluster`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseCreateAwsCluster._get_http_options() + + request, metadata = self._interceptor.pre_create_aws_cluster(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseCreateAwsCluster._get_transcoded_request(http_options, request) + + body = _BaseAwsClustersRestTransport._BaseCreateAwsCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseCreateAwsCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.CreateAwsCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "CreateAwsCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._CreateAwsCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_aws_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.create_aws_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "CreateAwsCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAwsNodePool(_BaseAwsClustersRestTransport._BaseCreateAwsNodePool, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.CreateAwsNodePool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: aws_service.CreateAwsNodePoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create aws node pool method over HTTP. + + Args: + request (~.aws_service.CreateAwsNodePoolRequest): + The request object. Response message for ``AwsClusters.CreateAwsNodePool`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseCreateAwsNodePool._get_http_options() + + request, metadata = self._interceptor.pre_create_aws_node_pool(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseCreateAwsNodePool._get_transcoded_request(http_options, request) + + body = _BaseAwsClustersRestTransport._BaseCreateAwsNodePool._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseCreateAwsNodePool._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.CreateAwsNodePool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "CreateAwsNodePool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._CreateAwsNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_aws_node_pool(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.create_aws_node_pool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "CreateAwsNodePool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAwsCluster(_BaseAwsClustersRestTransport._BaseDeleteAwsCluster, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.DeleteAwsCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: aws_service.DeleteAwsClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete aws cluster method over HTTP. + + Args: + request (~.aws_service.DeleteAwsClusterRequest): + The request object. Request message for ``AwsClusters.DeleteAwsCluster`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseDeleteAwsCluster._get_http_options() + + request, metadata = self._interceptor.pre_delete_aws_cluster(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseDeleteAwsCluster._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseDeleteAwsCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.DeleteAwsCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "DeleteAwsCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._DeleteAwsCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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_aws_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.delete_aws_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "DeleteAwsCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAwsNodePool(_BaseAwsClustersRestTransport._BaseDeleteAwsNodePool, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.DeleteAwsNodePool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: aws_service.DeleteAwsNodePoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete aws node pool method over HTTP. + + Args: + request (~.aws_service.DeleteAwsNodePoolRequest): + The request object. Request message for ``AwsClusters.DeleteAwsNodePool`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseDeleteAwsNodePool._get_http_options() + + request, metadata = self._interceptor.pre_delete_aws_node_pool(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseDeleteAwsNodePool._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseDeleteAwsNodePool._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.DeleteAwsNodePool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "DeleteAwsNodePool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._DeleteAwsNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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_aws_node_pool(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.delete_aws_node_pool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "DeleteAwsNodePool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateAwsAccessToken(_BaseAwsClustersRestTransport._BaseGenerateAwsAccessToken, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.GenerateAwsAccessToken") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: aws_service.GenerateAwsAccessTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> aws_service.GenerateAwsAccessTokenResponse: + r"""Call the generate aws access token method over HTTP. + + Args: + request (~.aws_service.GenerateAwsAccessTokenRequest): + The request object. Request message for + ``AwsClusters.GenerateAwsAccessToken`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.aws_service.GenerateAwsAccessTokenResponse: + Response message for + ``AwsClusters.GenerateAwsAccessToken`` method. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseGenerateAwsAccessToken._get_http_options() + + request, metadata = self._interceptor.pre_generate_aws_access_token(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseGenerateAwsAccessToken._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseGenerateAwsAccessToken._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GenerateAwsAccessToken", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GenerateAwsAccessToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._GenerateAwsAccessToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = aws_service.GenerateAwsAccessTokenResponse() + pb_resp = aws_service.GenerateAwsAccessTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_aws_access_token(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = aws_service.GenerateAwsAccessTokenResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.generate_aws_access_token", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GenerateAwsAccessToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateAwsClusterAgentToken(_BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.GenerateAwsClusterAgentToken") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: aws_service.GenerateAwsClusterAgentTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> aws_service.GenerateAwsClusterAgentTokenResponse: + r"""Call the generate aws cluster + agent token method over HTTP. + + Args: + request (~.aws_service.GenerateAwsClusterAgentTokenRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.aws_service.GenerateAwsClusterAgentTokenResponse: + + """ + + http_options = _BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken._get_http_options() + + request, metadata = self._interceptor.pre_generate_aws_cluster_agent_token(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken._get_transcoded_request(http_options, request) + + body = _BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GenerateAwsClusterAgentToken", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GenerateAwsClusterAgentToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._GenerateAwsClusterAgentToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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 = aws_service.GenerateAwsClusterAgentTokenResponse() + pb_resp = aws_service.GenerateAwsClusterAgentTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_aws_cluster_agent_token(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = aws_service.GenerateAwsClusterAgentTokenResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.generate_aws_cluster_agent_token", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GenerateAwsClusterAgentToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAwsCluster(_BaseAwsClustersRestTransport._BaseGetAwsCluster, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.GetAwsCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: aws_service.GetAwsClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> aws_resources.AwsCluster: + r"""Call the get aws cluster method over HTTP. + + Args: + request (~.aws_service.GetAwsClusterRequest): + The request object. Request message for ``AwsClusters.GetAwsCluster`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.aws_resources.AwsCluster: + An Anthos cluster running on AWS. + """ + + http_options = _BaseAwsClustersRestTransport._BaseGetAwsCluster._get_http_options() + + request, metadata = self._interceptor.pre_get_aws_cluster(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseGetAwsCluster._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseGetAwsCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetAwsCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetAwsCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._GetAwsCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = aws_resources.AwsCluster() + pb_resp = aws_resources.AwsCluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_aws_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = aws_resources.AwsCluster.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.get_aws_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetAwsCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAwsJsonWebKeys(_BaseAwsClustersRestTransport._BaseGetAwsJsonWebKeys, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.GetAwsJsonWebKeys") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: aws_service.GetAwsJsonWebKeysRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> aws_resources.AwsJsonWebKeys: + r"""Call the get aws json web keys method over HTTP. + + Args: + request (~.aws_service.GetAwsJsonWebKeysRequest): + The request object. GetAwsJsonWebKeysRequest gets the public component of + the keys used by the cluster to sign token requests. + This will be the jwks_uri for the discover document + returned by getOpenIDConfig. See the OpenID Connect + Discovery 1.0 specification for details. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.aws_resources.AwsJsonWebKeys: + AwsJsonWebKeys is a valid JSON Web + Key Set as specififed in RFC 7517. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseGetAwsJsonWebKeys._get_http_options() + + request, metadata = self._interceptor.pre_get_aws_json_web_keys(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseGetAwsJsonWebKeys._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseGetAwsJsonWebKeys._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetAwsJsonWebKeys", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetAwsJsonWebKeys", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._GetAwsJsonWebKeys._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = aws_resources.AwsJsonWebKeys() + pb_resp = aws_resources.AwsJsonWebKeys.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_aws_json_web_keys(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = aws_resources.AwsJsonWebKeys.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.get_aws_json_web_keys", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetAwsJsonWebKeys", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAwsNodePool(_BaseAwsClustersRestTransport._BaseGetAwsNodePool, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.GetAwsNodePool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: aws_service.GetAwsNodePoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> aws_resources.AwsNodePool: + r"""Call the get aws node pool method over HTTP. + + Args: + request (~.aws_service.GetAwsNodePoolRequest): + The request object. Request message for ``AwsClusters.GetAwsNodePool`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.aws_resources.AwsNodePool: + An Anthos node pool running on AWS. + """ + + http_options = _BaseAwsClustersRestTransport._BaseGetAwsNodePool._get_http_options() + + request, metadata = self._interceptor.pre_get_aws_node_pool(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseGetAwsNodePool._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseGetAwsNodePool._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetAwsNodePool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetAwsNodePool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._GetAwsNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = aws_resources.AwsNodePool() + pb_resp = aws_resources.AwsNodePool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_aws_node_pool(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = aws_resources.AwsNodePool.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.get_aws_node_pool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetAwsNodePool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAwsOpenIdConfig(_BaseAwsClustersRestTransport._BaseGetAwsOpenIdConfig, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.GetAwsOpenIdConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: aws_service.GetAwsOpenIdConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> aws_resources.AwsOpenIdConfig: + r"""Call the get aws open id config method over HTTP. + + Args: + request (~.aws_service.GetAwsOpenIdConfigRequest): + The request object. GetAwsOpenIdConfigRequest gets the + OIDC discovery document for the cluster. + See the OpenID Connect Discovery 1.0 + specification for details. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.aws_resources.AwsOpenIdConfig: + AwsOpenIdConfig is an OIDC discovery + document for the cluster. See the OpenID + Connect Discovery 1.0 specification for + details. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseGetAwsOpenIdConfig._get_http_options() + + request, metadata = self._interceptor.pre_get_aws_open_id_config(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseGetAwsOpenIdConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseGetAwsOpenIdConfig._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetAwsOpenIdConfig", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetAwsOpenIdConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._GetAwsOpenIdConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = aws_resources.AwsOpenIdConfig() + pb_resp = aws_resources.AwsOpenIdConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_aws_open_id_config(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = aws_resources.AwsOpenIdConfig.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.get_aws_open_id_config", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetAwsOpenIdConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAwsServerConfig(_BaseAwsClustersRestTransport._BaseGetAwsServerConfig, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.GetAwsServerConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: aws_service.GetAwsServerConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> aws_resources.AwsServerConfig: + r"""Call the get aws server config method over HTTP. + + Args: + request (~.aws_service.GetAwsServerConfigRequest): + The request object. GetAwsServerConfigRequest gets the + server config of GKE cluster on AWS. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.aws_resources.AwsServerConfig: + AwsServerConfig is the configuration + of GKE cluster on AWS. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseGetAwsServerConfig._get_http_options() + + request, metadata = self._interceptor.pre_get_aws_server_config(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseGetAwsServerConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseGetAwsServerConfig._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetAwsServerConfig", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetAwsServerConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._GetAwsServerConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = aws_resources.AwsServerConfig() + pb_resp = aws_resources.AwsServerConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_aws_server_config(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = aws_resources.AwsServerConfig.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.get_aws_server_config", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetAwsServerConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAwsClusters(_BaseAwsClustersRestTransport._BaseListAwsClusters, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.ListAwsClusters") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: aws_service.ListAwsClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> aws_service.ListAwsClustersResponse: + r"""Call the list aws clusters method over HTTP. + + Args: + request (~.aws_service.ListAwsClustersRequest): + The request object. Request message for ``AwsClusters.ListAwsClusters`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.aws_service.ListAwsClustersResponse: + Response message for ``AwsClusters.ListAwsClusters`` + method. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseListAwsClusters._get_http_options() + + request, metadata = self._interceptor.pre_list_aws_clusters(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseListAwsClusters._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseListAwsClusters._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.ListAwsClusters", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "ListAwsClusters", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._ListAwsClusters._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = aws_service.ListAwsClustersResponse() + pb_resp = aws_service.ListAwsClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_aws_clusters(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = aws_service.ListAwsClustersResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.list_aws_clusters", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "ListAwsClusters", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAwsNodePools(_BaseAwsClustersRestTransport._BaseListAwsNodePools, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.ListAwsNodePools") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: aws_service.ListAwsNodePoolsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> aws_service.ListAwsNodePoolsResponse: + r"""Call the list aws node pools method over HTTP. + + Args: + request (~.aws_service.ListAwsNodePoolsRequest): + The request object. Request message for ``AwsClusters.ListAwsNodePools`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.aws_service.ListAwsNodePoolsResponse: + Response message for ``AwsClusters.ListAwsNodePools`` + method. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseListAwsNodePools._get_http_options() + + request, metadata = self._interceptor.pre_list_aws_node_pools(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseListAwsNodePools._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseListAwsNodePools._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.ListAwsNodePools", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "ListAwsNodePools", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._ListAwsNodePools._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = aws_service.ListAwsNodePoolsResponse() + pb_resp = aws_service.ListAwsNodePoolsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_aws_node_pools(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = aws_service.ListAwsNodePoolsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.list_aws_node_pools", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "ListAwsNodePools", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RollbackAwsNodePoolUpdate(_BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.RollbackAwsNodePoolUpdate") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: aws_service.RollbackAwsNodePoolUpdateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the rollback aws node pool + update method over HTTP. + + Args: + request (~.aws_service.RollbackAwsNodePoolUpdateRequest): + The request object. Request message for + ``AwsClusters.RollbackAwsNodePoolUpdate`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate._get_http_options() + + request, metadata = self._interceptor.pre_rollback_aws_node_pool_update(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate._get_transcoded_request(http_options, request) + + body = _BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.RollbackAwsNodePoolUpdate", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "RollbackAwsNodePoolUpdate", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._RollbackAwsNodePoolUpdate._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_rollback_aws_node_pool_update(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.rollback_aws_node_pool_update", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "RollbackAwsNodePoolUpdate", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAwsCluster(_BaseAwsClustersRestTransport._BaseUpdateAwsCluster, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.UpdateAwsCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: aws_service.UpdateAwsClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update aws cluster method over HTTP. + + Args: + request (~.aws_service.UpdateAwsClusterRequest): + The request object. Request message for ``AwsClusters.UpdateAwsCluster`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseUpdateAwsCluster._get_http_options() + + request, metadata = self._interceptor.pre_update_aws_cluster(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseUpdateAwsCluster._get_transcoded_request(http_options, request) + + body = _BaseAwsClustersRestTransport._BaseUpdateAwsCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseUpdateAwsCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.UpdateAwsCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "UpdateAwsCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._UpdateAwsCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_aws_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.update_aws_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "UpdateAwsCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAwsNodePool(_BaseAwsClustersRestTransport._BaseUpdateAwsNodePool, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.UpdateAwsNodePool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: aws_service.UpdateAwsNodePoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update aws node pool method over HTTP. + + Args: + request (~.aws_service.UpdateAwsNodePoolRequest): + The request object. Request message for ``AwsClusters.UpdateAwsNodePool`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAwsClustersRestTransport._BaseUpdateAwsNodePool._get_http_options() + + request, metadata = self._interceptor.pre_update_aws_node_pool(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseUpdateAwsNodePool._get_transcoded_request(http_options, request) + + body = _BaseAwsClustersRestTransport._BaseUpdateAwsNodePool._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseUpdateAwsNodePool._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.UpdateAwsNodePool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "UpdateAwsNodePool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._UpdateAwsNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_aws_node_pool(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.update_aws_node_pool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "UpdateAwsNodePool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_aws_cluster(self) -> Callable[ + [aws_service.CreateAwsClusterRequest], + 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._CreateAwsCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_aws_node_pool(self) -> Callable[ + [aws_service.CreateAwsNodePoolRequest], + 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._CreateAwsNodePool(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_aws_cluster(self) -> Callable[ + [aws_service.DeleteAwsClusterRequest], + 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._DeleteAwsCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_aws_node_pool(self) -> Callable[ + [aws_service.DeleteAwsNodePoolRequest], + 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._DeleteAwsNodePool(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_aws_access_token(self) -> Callable[ + [aws_service.GenerateAwsAccessTokenRequest], + aws_service.GenerateAwsAccessTokenResponse]: + # 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._GenerateAwsAccessToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_aws_cluster_agent_token(self) -> Callable[ + [aws_service.GenerateAwsClusterAgentTokenRequest], + aws_service.GenerateAwsClusterAgentTokenResponse]: + # 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._GenerateAwsClusterAgentToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_aws_cluster(self) -> Callable[ + [aws_service.GetAwsClusterRequest], + aws_resources.AwsCluster]: + # 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._GetAwsCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_aws_json_web_keys(self) -> Callable[ + [aws_service.GetAwsJsonWebKeysRequest], + aws_resources.AwsJsonWebKeys]: + # 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._GetAwsJsonWebKeys(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_aws_node_pool(self) -> Callable[ + [aws_service.GetAwsNodePoolRequest], + aws_resources.AwsNodePool]: + # 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._GetAwsNodePool(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_aws_open_id_config(self) -> Callable[ + [aws_service.GetAwsOpenIdConfigRequest], + aws_resources.AwsOpenIdConfig]: + # 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._GetAwsOpenIdConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_aws_server_config(self) -> Callable[ + [aws_service.GetAwsServerConfigRequest], + aws_resources.AwsServerConfig]: + # 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._GetAwsServerConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_aws_clusters(self) -> Callable[ + [aws_service.ListAwsClustersRequest], + aws_service.ListAwsClustersResponse]: + # 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._ListAwsClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_aws_node_pools(self) -> Callable[ + [aws_service.ListAwsNodePoolsRequest], + aws_service.ListAwsNodePoolsResponse]: + # 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._ListAwsNodePools(self._session, self._host, self._interceptor) # type: ignore + + @property + def rollback_aws_node_pool_update(self) -> Callable[ + [aws_service.RollbackAwsNodePoolUpdateRequest], + 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._RollbackAwsNodePoolUpdate(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_aws_cluster(self) -> Callable[ + [aws_service.UpdateAwsClusterRequest], + 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._UpdateAwsCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_aws_node_pool(self) -> Callable[ + [aws_service.UpdateAwsNodePoolRequest], + 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._UpdateAwsNodePool(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseAwsClustersRestTransport._BaseCancelOperation, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAwsClustersRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseAwsClustersRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.CancelOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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(_BaseAwsClustersRestTransport._BaseDeleteOperation, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAwsClustersRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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(_BaseAwsClustersRestTransport._BaseGetOperation, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseAwsClustersRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseAwsClustersRestTransport._BaseListOperations, AwsClustersRestStub): + def __hash__(self): + return hash("AwsClustersRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseAwsClustersRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseAwsClustersRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAwsClustersRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.ListOperations", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AwsClustersRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AwsClustersAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AwsClustersRestTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest_base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest_base.py new file mode 100644 index 000000000000..011515166ec1 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest_base.py @@ -0,0 +1,834 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import AwsClustersTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.gke_multicloud_v1.types import aws_resources +from google.cloud.gke_multicloud_v1.types import aws_service +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseAwsClustersRestTransport(AwsClustersTransport): + """Base REST backend transport for AwsClusters. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 = 'gkemulticloud.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[Any]): 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. + 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 + 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 + ) + + class _BaseCreateAwsCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "awsClusterId" : "", } + + @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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/awsClusters', + 'body': 'aws_cluster', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.CreateAwsClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseCreateAwsCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseCreateAwsNodePool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "awsNodePoolId" : "", } + + @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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/awsClusters/*}/awsNodePools', + 'body': 'aws_node_pool', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.CreateAwsNodePoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseCreateAwsNodePool._get_unset_required_fields(query_params)) + + return query_params + + class _BaseDeleteAwsCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/awsClusters/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.DeleteAwsClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseDeleteAwsCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseDeleteAwsNodePool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/awsClusters/*/awsNodePools/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.DeleteAwsNodePoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseDeleteAwsNodePool._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGenerateAwsAccessToken: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{aws_cluster=projects/*/locations/*/awsClusters/*}:generateAwsAccessToken', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.GenerateAwsAccessTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseGenerateAwsAccessToken._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGenerateAwsClusterAgentToken: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{aws_cluster=projects/*/locations/*/awsClusters/*}:generateAwsClusterAgentToken', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.GenerateAwsClusterAgentTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAwsCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/awsClusters/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.GetAwsClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseGetAwsCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAwsJsonWebKeys: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{aws_cluster=projects/*/locations/*/awsClusters/*}/jwks', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.GetAwsJsonWebKeysRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseGetAwsJsonWebKeys._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAwsNodePool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/awsClusters/*/awsNodePools/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.GetAwsNodePoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseGetAwsNodePool._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAwsOpenIdConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{aws_cluster=projects/*/locations/*/awsClusters/*}/.well-known/openid-configuration', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.GetAwsOpenIdConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseGetAwsOpenIdConfig._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAwsServerConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/awsServerConfig}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.GetAwsServerConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseGetAwsServerConfig._get_unset_required_fields(query_params)) + + return query_params + + class _BaseListAwsClusters: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/awsClusters', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.ListAwsClustersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseListAwsClusters._get_unset_required_fields(query_params)) + + return query_params + + class _BaseListAwsNodePools: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/awsClusters/*}/awsNodePools', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.ListAwsNodePoolsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseListAwsNodePools._get_unset_required_fields(query_params)) + + return query_params + + class _BaseRollbackAwsNodePoolUpdate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/awsClusters/*/awsNodePools/*}:rollback', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.RollbackAwsNodePoolUpdateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate._get_unset_required_fields(query_params)) + + return query_params + + class _BaseUpdateAwsCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{aws_cluster.name=projects/*/locations/*/awsClusters/*}', + 'body': 'aws_cluster', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.UpdateAwsClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseUpdateAwsCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseUpdateAwsNodePool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{aws_node_pool.name=projects/*/locations/*/awsClusters/*/awsNodePools/*}', + 'body': 'aws_node_pool', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = aws_service.UpdateAwsNodePoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAwsClustersRestTransport._BaseUpdateAwsNodePool._get_unset_required_fields(query_params)) + + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseAwsClustersRestTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/__init__.py new file mode 100644 index 000000000000..b27d95ffef58 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AzureClustersClient +from .async_client import AzureClustersAsyncClient + +__all__ = ( + 'AzureClustersClient', + 'AzureClustersAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/async_client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/async_client.py new file mode 100644 index 000000000000..2adc9598d160 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/async_client.py @@ -0,0 +1,3034 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.gke_multicloud_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.gke_multicloud_v1.services.azure_clusters import pagers +from google.cloud.gke_multicloud_v1.types import azure_resources +from google.cloud.gke_multicloud_v1.types import azure_service +from google.cloud.gke_multicloud_v1.types import common_resources +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AzureClustersTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AzureClustersGrpcAsyncIOTransport +from .client import AzureClustersClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class AzureClustersAsyncClient: + """The AzureClusters API provides a single centrally managed + service to create and manage Anthos clusters that run on Azure + infrastructure. + """ + + _client: AzureClustersClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AzureClustersClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AzureClustersClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AzureClustersClient._DEFAULT_UNIVERSE + + azure_client_path = staticmethod(AzureClustersClient.azure_client_path) + parse_azure_client_path = staticmethod(AzureClustersClient.parse_azure_client_path) + azure_cluster_path = staticmethod(AzureClustersClient.azure_cluster_path) + parse_azure_cluster_path = staticmethod(AzureClustersClient.parse_azure_cluster_path) + azure_node_pool_path = staticmethod(AzureClustersClient.azure_node_pool_path) + parse_azure_node_pool_path = staticmethod(AzureClustersClient.parse_azure_node_pool_path) + azure_server_config_path = staticmethod(AzureClustersClient.azure_server_config_path) + parse_azure_server_config_path = staticmethod(AzureClustersClient.parse_azure_server_config_path) + common_billing_account_path = staticmethod(AzureClustersClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AzureClustersClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AzureClustersClient.common_folder_path) + parse_common_folder_path = staticmethod(AzureClustersClient.parse_common_folder_path) + common_organization_path = staticmethod(AzureClustersClient.common_organization_path) + parse_common_organization_path = staticmethod(AzureClustersClient.parse_common_organization_path) + common_project_path = staticmethod(AzureClustersClient.common_project_path) + parse_common_project_path = staticmethod(AzureClustersClient.parse_common_project_path) + common_location_path = staticmethod(AzureClustersClient.common_location_path) + parse_common_location_path = staticmethod(AzureClustersClient.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: + AzureClustersAsyncClient: The constructed client. + """ + return AzureClustersClient.from_service_account_info.__func__(AzureClustersAsyncClient, 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: + AzureClustersAsyncClient: The constructed client. + """ + return AzureClustersClient.from_service_account_file.__func__(AzureClustersAsyncClient, 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 AzureClustersClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AzureClustersTransport: + """Returns the transport used by the client instance. + + Returns: + AzureClustersTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = AzureClustersClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AzureClustersTransport, Callable[..., AzureClustersTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the azure clusters async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AzureClustersTransport,Callable[..., AzureClustersTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AzureClustersTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AzureClustersClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.gkemulticloud_v1.AzureClustersAsyncClient`.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "credentialsType": None, + } + ) + + async def create_azure_client(self, + request: Optional[Union[azure_service.CreateAzureClientRequest, dict]] = None, + *, + parent: Optional[str] = None, + azure_client: Optional[azure_resources.AzureClient] = None, + azure_client_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource on a given Google Cloud project and region. + + ``AzureClient`` resources hold client authentication information + needed by the Anthos Multicloud API to manage Azure resources on + your Azure subscription on your behalf. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_create_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + azure_client = gke_multicloud_v1.AzureClient() + azure_client.tenant_id = "tenant_id_value" + azure_client.application_id = "application_id_value" + + request = gke_multicloud_v1.CreateAzureClientRequest( + parent="parent_value", + azure_client=azure_client, + azure_client_id="azure_client_id_value", + ) + + # Make the request + operation = client.create_azure_client(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAzureClientRequest, dict]]): + The request object. Request message for ``AzureClusters.CreateAzureClient`` + method. + parent (:class:`str`): + Required. The parent location where this + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_client (:class:`google.cloud.gke_multicloud_v1.types.AzureClient`): + Required. The specification of the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + to create. + + This corresponds to the ``azure_client`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_client_id (:class:`str`): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource name formatted as + ``projects//locations//azureClients/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``azure_client_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AzureClient` AzureClient resources hold client authentication information needed by the + Anthos Multi-Cloud API to manage Azure resources on + your Azure subscription. + + When an + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + is created, an AzureClient resource needs to be + provided and all operations on Azure resources + associated to that cluster will authenticate to Azure + services using the given client. + + AzureClient resources are immutable and cannot be + modified upon creation. + + Each AzureClient resource is bound to a single Azure + Active Directory Application and tenant. + + """ + # 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, azure_client, azure_client_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.CreateAzureClientRequest): + request = azure_service.CreateAzureClientRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if azure_client is not None: + request.azure_client = azure_client + if azure_client_id is not None: + request.azure_client_id = azure_client_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_azure_client] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + azure_resources.AzureClient, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_azure_client(self, + request: Optional[Union[azure_service.GetAzureClientRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureClient: + r"""Describes a specific + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + 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 gke_multicloud_v1 + + async def sample_get_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureClientRequest( + name="name_value", + ) + + # Make the request + response = await client.get_azure_client(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureClientRequest, dict]]): + The request object. Request message for ``AzureClusters.GetAzureClient`` + method. + name (:class:`str`): + Required. The name of the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource to describe. + + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + names are formatted as + ``projects//locations//azureClients/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureClient: + AzureClient resources hold client authentication information needed by the + Anthos Multi-Cloud API to manage Azure resources on + your Azure subscription. + + When an + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + is created, an AzureClient resource needs to be + provided and all operations on Azure resources + associated to that cluster will authenticate to Azure + services using the given client. + + AzureClient resources are immutable and cannot be + modified upon creation. + + Each AzureClient resource is bound to a single Azure + Active Directory Application and tenant. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureClientRequest): + request = azure_service.GetAzureClientRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_client] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_azure_clients(self, + request: Optional[Union[azure_service.ListAzureClientsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAzureClientsAsyncPager: + r"""Lists all + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resources on a given Google Cloud project and region. + + .. 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 gke_multicloud_v1 + + async def sample_list_azure_clients(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureClientsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_clients(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest, dict]]): + The request object. Request message for ``AzureClusters.ListAzureClients`` + method. + parent (:class:`str`): + Required. The parent location which owns this collection + of + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClientsAsyncPager: + Response message for AzureClusters.ListAzureClients + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.ListAzureClientsRequest): + request = azure_service.ListAzureClientsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_azure_clients] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAzureClientsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_azure_client(self, + request: Optional[Union[azure_service.DeleteAzureClientRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a specific + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource. + + If the client is used by one or more clusters, deletion will + fail and a ``FAILED_PRECONDITION`` error will be returned. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_delete_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureClientRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_client(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAzureClientRequest, dict]]): + The request object. Request message for ``AzureClusters.DeleteAzureClient`` + method. + name (:class:`str`): + Required. The resource name the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + to delete. + + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + names are formatted as + ``projects//locations//azureClients/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.DeleteAzureClientRequest): + request = azure_service.DeleteAzureClientRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_azure_client] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_azure_cluster(self, + request: Optional[Union[azure_service.CreateAzureClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + azure_cluster: Optional[azure_resources.AzureCluster] = None, + azure_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_create_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + azure_cluster = gke_multicloud_v1.AzureCluster() + azure_cluster.azure_region = "azure_region_value" + azure_cluster.resource_group_id = "resource_group_id_value" + azure_cluster.networking.virtual_network_id = "virtual_network_id_value" + azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + azure_cluster.control_plane.version = "version_value" + azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" + azure_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAzureClusterRequest( + parent="parent_value", + azure_cluster=azure_cluster, + azure_cluster_id="azure_cluster_id_value", + ) + + # Make the request + operation = client.create_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAzureClusterRequest, dict]]): + The request object. Request message for ``AzureClusters.CreateAzureCluster`` + method. + parent (:class:`str`): + Required. The parent location where this + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_cluster (:class:`google.cloud.gke_multicloud_v1.types.AzureCluster`): + Required. The specification of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + to create. + + This corresponds to the ``azure_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_cluster_id (:class:`str`): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource name formatted as + ``projects//locations//azureClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``azure_cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AzureCluster` + An Anthos cluster running on Azure. + + """ + # 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, azure_cluster, azure_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.CreateAzureClusterRequest): + request = azure_service.CreateAzureClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if azure_cluster is not None: + request.azure_cluster = azure_cluster + if azure_cluster_id is not None: + request.azure_cluster_id = azure_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_azure_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + azure_resources.AzureCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_azure_cluster(self, + request: Optional[Union[azure_service.UpdateAzureClusterRequest, dict]] = None, + *, + azure_cluster: Optional[azure_resources.AzureCluster] = 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, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + .. 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 gke_multicloud_v1 + + async def sample_update_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + azure_cluster = gke_multicloud_v1.AzureCluster() + azure_cluster.azure_region = "azure_region_value" + azure_cluster.resource_group_id = "resource_group_id_value" + azure_cluster.networking.virtual_network_id = "virtual_network_id_value" + azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + azure_cluster.control_plane.version = "version_value" + azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" + azure_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAzureClusterRequest( + azure_cluster=azure_cluster, + ) + + # Make the request + operation = client.update_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.UpdateAzureClusterRequest, dict]]): + The request object. Request message for ``AzureClusters.UpdateAzureCluster`` + method. + azure_cluster (:class:`google.cloud.gke_multicloud_v1.types.AzureCluster`): + Required. The + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource to update. + + This corresponds to the ``azure_cluster`` 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 path + must be supplied in this field. The elements of the + repeated paths field can only include these fields from + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]: + + - ``description``. + - ``azureClient``. + - ``control_plane.version``. + - ``control_plane.vm_size``. + - ``annotations``. + - ``authorization.admin_users``. + - ``authorization.admin_groups``. + - ``control_plane.root_volume.size_gib``. + - ``azure_services_authentication``. + - ``azure_services_authentication.tenant_id``. + - ``azure_services_authentication.application_id``. + - ``control_plane.proxy_config``. + - ``control_plane.proxy_config.resource_group_id``. + - ``control_plane.proxy_config.secret_id``. + - ``control_plane.ssh_config.authorized_key``. + - ``logging_config.component_config.enable_components`` + - ``monitoring_config.managed_prometheus_config.enabled``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AzureCluster` + An Anthos cluster running on Azure. + + """ + # 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([azure_cluster, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.UpdateAzureClusterRequest): + request = azure_service.UpdateAzureClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if azure_cluster is not None: + request.azure_cluster = azure_cluster + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_azure_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_cluster.name", request.azure_cluster.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + azure_resources.AzureCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_azure_cluster(self, + request: Optional[Union[azure_service.GetAzureClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureCluster: + r"""Describes a specific + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + 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 gke_multicloud_v1 + + async def sample_get_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_azure_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureClusterRequest, dict]]): + The request object. Request message for ``AzureClusters.GetAzureCluster`` + method. + name (:class:`str`): + Required. The name of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource to describe. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureCluster: + An Anthos cluster running on Azure. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureClusterRequest): + request = azure_service.GetAzureClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_azure_clusters(self, + request: Optional[Union[azure_service.ListAzureClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAzureClustersAsyncPager: + r"""Lists all + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resources on a given Google Cloud project and region. + + .. 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 gke_multicloud_v1 + + async def sample_list_azure_clusters(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest, dict]]): + The request object. Request message for ``AzureClusters.ListAzureClusters`` + method. + parent (:class:`str`): + Required. The parent location which owns this collection + of + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClustersAsyncPager: + Response message for AzureClusters.ListAzureClusters + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.ListAzureClustersRequest): + request = azure_service.ListAzureClustersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_azure_clusters] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAzureClustersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_azure_cluster(self, + request: Optional[Union[azure_service.DeleteAzureClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a specific + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource. + + Fails if the cluster has one or more associated + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_delete_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAzureClusterRequest, dict]]): + The request object. Request message for ``AzureClusters.DeleteAzureCluster`` + method. + name (:class:`str`): + Required. The resource name the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + to delete. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.DeleteAzureClusterRequest): + request = azure_service.DeleteAzureClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_azure_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_azure_cluster_agent_token(self, + request: Optional[Union[azure_service.GenerateAzureClusterAgentTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_service.GenerateAzureClusterAgentTokenResponse: + r"""Generates an access token for a cluster agent. + + .. 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 gke_multicloud_v1 + + async def sample_generate_azure_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAzureClusterAgentTokenRequest( + azure_cluster="azure_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = await client.generate_azure_cluster_agent_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenRequest, dict]]): + The request object. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenResponse: + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GenerateAzureClusterAgentTokenRequest): + request = azure_service.GenerateAzureClusterAgentTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_azure_cluster_agent_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_cluster", request.azure_cluster), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_azure_access_token(self, + request: Optional[Union[azure_service.GenerateAzureAccessTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_service.GenerateAzureAccessTokenResponse: + r"""Generates a short-lived access token to authenticate to a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + 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 gke_multicloud_v1 + + async def sample_generate_azure_access_token(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAzureAccessTokenRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = await client.generate_azure_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenRequest, dict]]): + The request object. Request message for + ``AzureClusters.GenerateAzureAccessToken`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenResponse: + Response message for + AzureClusters.GenerateAzureAccessToken method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GenerateAzureAccessTokenRequest): + request = azure_service.GenerateAzureAccessTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_azure_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_cluster", request.azure_cluster), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_azure_node_pool(self, + request: Optional[Union[azure_service.CreateAzureNodePoolRequest, dict]] = None, + *, + parent: Optional[str] = None, + azure_node_pool: Optional[azure_resources.AzureNodePool] = None, + azure_node_pool_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool], + attached to a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_create_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + azure_node_pool = gke_multicloud_v1.AzureNodePool() + azure_node_pool.version = "version_value" + azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" + azure_node_pool.subnet_id = "subnet_id_value" + azure_node_pool.autoscaling.min_node_count = 1489 + azure_node_pool.autoscaling.max_node_count = 1491 + azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.CreateAzureNodePoolRequest( + parent="parent_value", + azure_node_pool=azure_node_pool, + azure_node_pool_id="azure_node_pool_id_value", + ) + + # Make the request + operation = client.create_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAzureNodePoolRequest, dict]]): + The request object. Response message for + ``AzureClusters.CreateAzureNodePool`` method. + parent (:class:`str`): + Required. The + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource where this node pool will be created. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_node_pool (:class:`google.cloud.gke_multicloud_v1.types.AzureNodePool`): + Required. The specification of the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + to create. + + This corresponds to the ``azure_node_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_node_pool_id (:class:`str`): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource name formatted as + ``projects//locations//azureClusters//azureNodePools/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``azure_node_pool_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AzureNodePool` + An Anthos node pool running on Azure. + + """ + # 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, azure_node_pool, azure_node_pool_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.CreateAzureNodePoolRequest): + request = azure_service.CreateAzureNodePoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if azure_node_pool is not None: + request.azure_node_pool = azure_node_pool + if azure_node_pool_id is not None: + request.azure_node_pool_id = azure_node_pool_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_azure_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + azure_resources.AzureNodePool, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_azure_node_pool(self, + request: Optional[Union[azure_service.UpdateAzureNodePoolRequest, dict]] = None, + *, + azure_node_pool: Optional[azure_resources.AzureNodePool] = 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, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates an + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. + + .. 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 gke_multicloud_v1 + + async def sample_update_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + azure_node_pool = gke_multicloud_v1.AzureNodePool() + azure_node_pool.version = "version_value" + azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" + azure_node_pool.subnet_id = "subnet_id_value" + azure_node_pool.autoscaling.min_node_count = 1489 + azure_node_pool.autoscaling.max_node_count = 1491 + azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.UpdateAzureNodePoolRequest( + azure_node_pool=azure_node_pool, + ) + + # Make the request + operation = client.update_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.UpdateAzureNodePoolRequest, dict]]): + The request object. Request message for + ``AzureClusters.UpdateAzureNodePool`` method. + azure_node_pool (:class:`google.cloud.gke_multicloud_v1.types.AzureNodePool`): + Required. The + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource to update. + + This corresponds to the ``azure_node_pool`` 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 path + must be supplied in this field. The elements of the + repeated paths field can only include these fields from + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]: + + \*. ``annotations``. + + - ``version``. + - ``autoscaling.min_node_count``. + - ``autoscaling.max_node_count``. + - ``config.ssh_config.authorized_key``. + - ``management.auto_repair``. + - ``management``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.gke_multicloud_v1.types.AzureNodePool` + An Anthos node pool running on Azure. + + """ + # 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([azure_node_pool, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.UpdateAzureNodePoolRequest): + request = azure_service.UpdateAzureNodePoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if azure_node_pool is not None: + request.azure_node_pool = azure_node_pool + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_azure_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_node_pool.name", request.azure_node_pool.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + azure_resources.AzureNodePool, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_azure_node_pool(self, + request: Optional[Union[azure_service.GetAzureNodePoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureNodePool: + r"""Describes a specific + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + 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 gke_multicloud_v1 + + async def sample_get_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureNodePoolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_azure_node_pool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureNodePoolRequest, dict]]): + The request object. Request message for ``AzureClusters.GetAzureNodePool`` + method. + name (:class:`str`): + Required. The name of the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource to describe. + + ``AzureNodePool`` names are formatted as + ``projects//locations//azureClusters//azureNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureNodePool: + An Anthos node pool running on Azure. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureNodePoolRequest): + request = azure_service.GetAzureNodePoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_azure_node_pools(self, + request: Optional[Union[azure_service.ListAzureNodePoolsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAzureNodePoolsAsyncPager: + r"""Lists all + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources on a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + .. 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 gke_multicloud_v1 + + async def sample_list_azure_node_pools(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureNodePoolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_node_pools(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest, dict]]): + The request object. Request message for ``AzureClusters.ListAzureNodePools`` + method. + parent (:class:`str`): + Required. The parent ``AzureCluster`` which owns this + collection of + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureNodePoolsAsyncPager: + Response message for AzureClusters.ListAzureNodePools + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.ListAzureNodePoolsRequest): + request = azure_service.ListAzureNodePoolsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_azure_node_pools] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAzureNodePoolsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_azure_node_pool(self, + request: Optional[Union[azure_service.DeleteAzureNodePoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a specific + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + async def sample_delete_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureNodePoolRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAzureNodePoolRequest, dict]]): + The request object. Request message for + ``AzureClusters.DeleteAzureNodePool`` method. + name (:class:`str`): + Required. The resource name the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + to delete. + + ``AzureNodePool`` names are formatted as + ``projects//locations//azureClusters//azureNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.DeleteAzureNodePoolRequest): + request = azure_service.DeleteAzureNodePoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_azure_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_azure_open_id_config(self, + request: Optional[Union[azure_service.GetAzureOpenIdConfigRequest, dict]] = None, + *, + azure_cluster: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureOpenIdConfig: + r"""Gets the OIDC discovery document for the cluster. See the + `OpenID Connect Discovery 1.0 + specification `__ + for details. + + .. 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 gke_multicloud_v1 + + async def sample_get_azure_open_id_config(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureOpenIdConfigRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = await client.get_azure_open_id_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureOpenIdConfigRequest, dict]]): + The request object. GetAzureOpenIdConfigRequest gets the + OIDC discovery document for the cluster. + See the OpenID Connect Discovery 1.0 + specification for details. + azure_cluster (:class:`str`): + Required. The AzureCluster, which + owns the OIDC discovery document. + Format: + + projects//locations//azureClusters/ + + This corresponds to the ``azure_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureOpenIdConfig: + AzureOpenIdConfig is an OIDC + discovery document for the cluster. See + the OpenID Connect Discovery 1.0 + specification for details. + + """ + # 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([azure_cluster]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureOpenIdConfigRequest): + request = azure_service.GetAzureOpenIdConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if azure_cluster is not None: + request.azure_cluster = azure_cluster + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_open_id_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_cluster", request.azure_cluster), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_azure_json_web_keys(self, + request: Optional[Union[azure_service.GetAzureJsonWebKeysRequest, dict]] = None, + *, + azure_cluster: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureJsonWebKeys: + r"""Gets the public component of the cluster signing keys + in JSON Web Key format. + + .. 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 gke_multicloud_v1 + + async def sample_get_azure_json_web_keys(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureJsonWebKeysRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = await client.get_azure_json_web_keys(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureJsonWebKeysRequest, dict]]): + The request object. GetAzureJsonWebKeysRequest gets the public component of + the keys used by the cluster to sign token requests. + This will be the jwks_uri for the discover document + returned by getOpenIDConfig. See the OpenID Connect + Discovery 1.0 specification for details. + azure_cluster (:class:`str`): + Required. The AzureCluster, which owns the JsonWebKeys. + Format: + ``projects//locations//azureClusters/`` + + This corresponds to the ``azure_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureJsonWebKeys: + AzureJsonWebKeys is a valid JSON Web + Key Set as specififed in RFC 7517. + + """ + # 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([azure_cluster]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureJsonWebKeysRequest): + request = azure_service.GetAzureJsonWebKeysRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if azure_cluster is not None: + request.azure_cluster = azure_cluster + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_json_web_keys] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_cluster", request.azure_cluster), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_azure_server_config(self, + request: Optional[Union[azure_service.GetAzureServerConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureServerConfig: + r"""Returns information, such as supported Azure regions + and Kubernetes versions, on a given Google Cloud + 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 gke_multicloud_v1 + + async def sample_get_azure_server_config(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureServerConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_azure_server_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureServerConfigRequest, dict]]): + The request object. GetAzureServerConfigRequest gets the + server config of GKE cluster on Azure. + name (:class:`str`): + Required. The name of the + [AzureServerConfig][google.cloud.gkemulticloud.v1.AzureServerConfig] + resource to describe. + + ``AzureServerConfig`` names are formatted as + ``projects//locations//azureServerConfig``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureServerConfig: + AzureServerConfig contains + information about a Google Cloud + location, such as supported Azure + regions and Kubernetes versions. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureServerConfigRequest): + request = azure_service.GetAzureServerConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_server_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_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, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def 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, Union[str, bytes]]] = (), + ) -> 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + 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, Union[str, bytes]]] = (), + ) -> 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "AzureClustersAsyncClient": + 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__ = ( + "AzureClustersAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/client.py new file mode 100644 index 000000000000..1db56d2a8421 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/client.py @@ -0,0 +1,3380 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.gke_multicloud_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.gke_multicloud_v1.services.azure_clusters import pagers +from google.cloud.gke_multicloud_v1.types import azure_resources +from google.cloud.gke_multicloud_v1.types import azure_service +from google.cloud.gke_multicloud_v1.types import common_resources +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AzureClustersTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AzureClustersGrpcTransport +from .transports.grpc_asyncio import AzureClustersGrpcAsyncIOTransport +from .transports.rest import AzureClustersRestTransport + + +class AzureClustersClientMeta(type): + """Metaclass for the AzureClusters 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[AzureClustersTransport]] + _transport_registry["grpc"] = AzureClustersGrpcTransport + _transport_registry["grpc_asyncio"] = AzureClustersGrpcAsyncIOTransport + _transport_registry["rest"] = AzureClustersRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AzureClustersTransport]: + """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 AzureClustersClient(metaclass=AzureClustersClientMeta): + """The AzureClusters API provides a single centrally managed + service to create and manage Anthos clusters that run on Azure + infrastructure. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "gkemulticloud.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "gkemulticloud.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AzureClustersClient: 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: + AzureClustersClient: 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) -> AzureClustersTransport: + """Returns the transport used by the client instance. + + Returns: + AzureClustersTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def azure_client_path(project: str,location: str,azure_client: str,) -> str: + """Returns a fully-qualified azure_client string.""" + return "projects/{project}/locations/{location}/azureClients/{azure_client}".format(project=project, location=location, azure_client=azure_client, ) + + @staticmethod + def parse_azure_client_path(path: str) -> Dict[str,str]: + """Parses a azure_client path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/azureClients/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def azure_cluster_path(project: str,location: str,azure_cluster: str,) -> str: + """Returns a fully-qualified azure_cluster string.""" + return "projects/{project}/locations/{location}/azureClusters/{azure_cluster}".format(project=project, location=location, azure_cluster=azure_cluster, ) + + @staticmethod + def parse_azure_cluster_path(path: str) -> Dict[str,str]: + """Parses a azure_cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/azureClusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def azure_node_pool_path(project: str,location: str,azure_cluster: str,azure_node_pool: str,) -> str: + """Returns a fully-qualified azure_node_pool string.""" + return "projects/{project}/locations/{location}/azureClusters/{azure_cluster}/azureNodePools/{azure_node_pool}".format(project=project, location=location, azure_cluster=azure_cluster, azure_node_pool=azure_node_pool, ) + + @staticmethod + def parse_azure_node_pool_path(path: str) -> Dict[str,str]: + """Parses a azure_node_pool path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/azureClusters/(?P.+?)/azureNodePools/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def azure_server_config_path(project: str,location: str,) -> str: + """Returns a fully-qualified azure_server_config string.""" + return "projects/{project}/locations/{location}/azureServerConfig".format(project=project, location=location, ) + + @staticmethod + def parse_azure_server_config_path(path: str) -> Dict[str,str]: + """Parses a azure_server_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/azureServerConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = AzureClustersClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AzureClustersClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AzureClustersClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AzureClustersTransport, Callable[..., AzureClustersTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the azure clusters client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AzureClustersTransport,Callable[..., AzureClustersTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AzureClustersTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AzureClustersClient._read_environment_variables() + self._client_cert_source = AzureClustersClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AzureClustersClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AzureClustersTransport) + if transport_provided: + # transport is a AzureClustersTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(AzureClustersTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AzureClustersClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[AzureClustersTransport], Callable[..., AzureClustersTransport]] = ( + AzureClustersClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AzureClustersTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.gkemulticloud_v1.AzureClustersClient`.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "credentialsType": None, + } + ) + + def create_azure_client(self, + request: Optional[Union[azure_service.CreateAzureClientRequest, dict]] = None, + *, + parent: Optional[str] = None, + azure_client: Optional[azure_resources.AzureClient] = None, + azure_client_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource on a given Google Cloud project and region. + + ``AzureClient`` resources hold client authentication information + needed by the Anthos Multicloud API to manage Azure resources on + your Azure subscription on your behalf. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_create_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + azure_client = gke_multicloud_v1.AzureClient() + azure_client.tenant_id = "tenant_id_value" + azure_client.application_id = "application_id_value" + + request = gke_multicloud_v1.CreateAzureClientRequest( + parent="parent_value", + azure_client=azure_client, + azure_client_id="azure_client_id_value", + ) + + # Make the request + operation = client.create_azure_client(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.CreateAzureClientRequest, dict]): + The request object. Request message for ``AzureClusters.CreateAzureClient`` + method. + parent (str): + Required. The parent location where this + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_client (google.cloud.gke_multicloud_v1.types.AzureClient): + Required. The specification of the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + to create. + + This corresponds to the ``azure_client`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_client_id (str): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource name formatted as + ``projects//locations//azureClients/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``azure_client_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.gke_multicloud_v1.types.AzureClient` AzureClient resources hold client authentication information needed by the + Anthos Multi-Cloud API to manage Azure resources on + your Azure subscription. + + When an + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + is created, an AzureClient resource needs to be + provided and all operations on Azure resources + associated to that cluster will authenticate to Azure + services using the given client. + + AzureClient resources are immutable and cannot be + modified upon creation. + + Each AzureClient resource is bound to a single Azure + Active Directory Application and tenant. + + """ + # 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, azure_client, azure_client_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.CreateAzureClientRequest): + request = azure_service.CreateAzureClientRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if azure_client is not None: + request.azure_client = azure_client + if azure_client_id is not None: + request.azure_client_id = azure_client_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_azure_client] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + azure_resources.AzureClient, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_azure_client(self, + request: Optional[Union[azure_service.GetAzureClientRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureClient: + r"""Describes a specific + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + 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 gke_multicloud_v1 + + def sample_get_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureClientRequest( + name="name_value", + ) + + # Make the request + response = client.get_azure_client(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAzureClientRequest, dict]): + The request object. Request message for ``AzureClusters.GetAzureClient`` + method. + name (str): + Required. The name of the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource to describe. + + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + names are formatted as + ``projects//locations//azureClients/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureClient: + AzureClient resources hold client authentication information needed by the + Anthos Multi-Cloud API to manage Azure resources on + your Azure subscription. + + When an + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + is created, an AzureClient resource needs to be + provided and all operations on Azure resources + associated to that cluster will authenticate to Azure + services using the given client. + + AzureClient resources are immutable and cannot be + modified upon creation. + + Each AzureClient resource is bound to a single Azure + Active Directory Application and tenant. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureClientRequest): + request = azure_service.GetAzureClientRequest(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_azure_client] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_azure_clients(self, + request: Optional[Union[azure_service.ListAzureClientsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAzureClientsPager: + r"""Lists all + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resources on a given Google Cloud project and region. + + .. 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 gke_multicloud_v1 + + def sample_list_azure_clients(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureClientsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_clients(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest, dict]): + The request object. Request message for ``AzureClusters.ListAzureClients`` + method. + parent (str): + Required. The parent location which owns this collection + of + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClientsPager: + Response message for AzureClusters.ListAzureClients + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.ListAzureClientsRequest): + request = azure_service.ListAzureClientsRequest(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_azure_clients] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAzureClientsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_azure_client(self, + request: Optional[Union[azure_service.DeleteAzureClientRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a specific + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource. + + If the client is used by one or more clusters, deletion will + fail and a ``FAILED_PRECONDITION`` error will be returned. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_delete_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureClientRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_client(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.DeleteAzureClientRequest, dict]): + The request object. Request message for ``AzureClusters.DeleteAzureClient`` + method. + name (str): + Required. The resource name the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + to delete. + + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + names are formatted as + ``projects//locations//azureClients/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.DeleteAzureClientRequest): + request = azure_service.DeleteAzureClientRequest(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_azure_client] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_azure_cluster(self, + request: Optional[Union[azure_service.CreateAzureClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + azure_cluster: Optional[azure_resources.AzureCluster] = None, + azure_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_create_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + azure_cluster = gke_multicloud_v1.AzureCluster() + azure_cluster.azure_region = "azure_region_value" + azure_cluster.resource_group_id = "resource_group_id_value" + azure_cluster.networking.virtual_network_id = "virtual_network_id_value" + azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + azure_cluster.control_plane.version = "version_value" + azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" + azure_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAzureClusterRequest( + parent="parent_value", + azure_cluster=azure_cluster, + azure_cluster_id="azure_cluster_id_value", + ) + + # Make the request + operation = client.create_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.CreateAzureClusterRequest, dict]): + The request object. Request message for ``AzureClusters.CreateAzureCluster`` + method. + parent (str): + Required. The parent location where this + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_cluster (google.cloud.gke_multicloud_v1.types.AzureCluster): + Required. The specification of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + to create. + + This corresponds to the ``azure_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_cluster_id (str): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource name formatted as + ``projects//locations//azureClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``azure_cluster_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AzureCluster` + An Anthos cluster running on Azure. + + """ + # 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, azure_cluster, azure_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.CreateAzureClusterRequest): + request = azure_service.CreateAzureClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if azure_cluster is not None: + request.azure_cluster = azure_cluster + if azure_cluster_id is not None: + request.azure_cluster_id = azure_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_azure_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + azure_resources.AzureCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_azure_cluster(self, + request: Optional[Union[azure_service.UpdateAzureClusterRequest, dict]] = None, + *, + azure_cluster: Optional[azure_resources.AzureCluster] = 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, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates an + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + .. 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 gke_multicloud_v1 + + def sample_update_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + azure_cluster = gke_multicloud_v1.AzureCluster() + azure_cluster.azure_region = "azure_region_value" + azure_cluster.resource_group_id = "resource_group_id_value" + azure_cluster.networking.virtual_network_id = "virtual_network_id_value" + azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + azure_cluster.control_plane.version = "version_value" + azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" + azure_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAzureClusterRequest( + azure_cluster=azure_cluster, + ) + + # Make the request + operation = client.update_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.UpdateAzureClusterRequest, dict]): + The request object. Request message for ``AzureClusters.UpdateAzureCluster`` + method. + azure_cluster (google.cloud.gke_multicloud_v1.types.AzureCluster): + Required. The + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource to update. + + This corresponds to the ``azure_cluster`` 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 path + must be supplied in this field. The elements of the + repeated paths field can only include these fields from + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]: + + - ``description``. + - ``azureClient``. + - ``control_plane.version``. + - ``control_plane.vm_size``. + - ``annotations``. + - ``authorization.admin_users``. + - ``authorization.admin_groups``. + - ``control_plane.root_volume.size_gib``. + - ``azure_services_authentication``. + - ``azure_services_authentication.tenant_id``. + - ``azure_services_authentication.application_id``. + - ``control_plane.proxy_config``. + - ``control_plane.proxy_config.resource_group_id``. + - ``control_plane.proxy_config.secret_id``. + - ``control_plane.ssh_config.authorized_key``. + - ``logging_config.component_config.enable_components`` + - ``monitoring_config.managed_prometheus_config.enabled``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AzureCluster` + An Anthos cluster running on Azure. + + """ + # 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([azure_cluster, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.UpdateAzureClusterRequest): + request = azure_service.UpdateAzureClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if azure_cluster is not None: + request.azure_cluster = azure_cluster + 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_azure_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_cluster.name", request.azure_cluster.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + azure_resources.AzureCluster, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_azure_cluster(self, + request: Optional[Union[azure_service.GetAzureClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureCluster: + r"""Describes a specific + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + 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 gke_multicloud_v1 + + def sample_get_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_azure_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAzureClusterRequest, dict]): + The request object. Request message for ``AzureClusters.GetAzureCluster`` + method. + name (str): + Required. The name of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource to describe. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureCluster: + An Anthos cluster running on Azure. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureClusterRequest): + request = azure_service.GetAzureClusterRequest(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_azure_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_azure_clusters(self, + request: Optional[Union[azure_service.ListAzureClustersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAzureClustersPager: + r"""Lists all + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resources on a given Google Cloud project and region. + + .. 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 gke_multicloud_v1 + + def sample_list_azure_clusters(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest, dict]): + The request object. Request message for ``AzureClusters.ListAzureClusters`` + method. + parent (str): + Required. The parent location which owns this collection + of + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClustersPager: + Response message for AzureClusters.ListAzureClusters + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.ListAzureClustersRequest): + request = azure_service.ListAzureClustersRequest(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_azure_clusters] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAzureClustersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_azure_cluster(self, + request: Optional[Union[azure_service.DeleteAzureClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a specific + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource. + + Fails if the cluster has one or more associated + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_delete_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.DeleteAzureClusterRequest, dict]): + The request object. Request message for ``AzureClusters.DeleteAzureCluster`` + method. + name (str): + Required. The resource name the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + to delete. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource + names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.DeleteAzureClusterRequest): + request = azure_service.DeleteAzureClusterRequest(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_azure_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_azure_cluster_agent_token(self, + request: Optional[Union[azure_service.GenerateAzureClusterAgentTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_service.GenerateAzureClusterAgentTokenResponse: + r"""Generates an access token for a cluster agent. + + .. 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 gke_multicloud_v1 + + def sample_generate_azure_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAzureClusterAgentTokenRequest( + azure_cluster="azure_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = client.generate_azure_cluster_agent_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenRequest, dict]): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenResponse: + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GenerateAzureClusterAgentTokenRequest): + request = azure_service.GenerateAzureClusterAgentTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_azure_cluster_agent_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_cluster", request.azure_cluster), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_azure_access_token(self, + request: Optional[Union[azure_service.GenerateAzureAccessTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_service.GenerateAzureAccessTokenResponse: + r"""Generates a short-lived access token to authenticate to a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + 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 gke_multicloud_v1 + + def sample_generate_azure_access_token(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAzureAccessTokenRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = client.generate_azure_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenRequest, dict]): + The request object. Request message for + ``AzureClusters.GenerateAzureAccessToken`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenResponse: + Response message for + AzureClusters.GenerateAzureAccessToken method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GenerateAzureAccessTokenRequest): + request = azure_service.GenerateAzureAccessTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_azure_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_cluster", request.azure_cluster), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_azure_node_pool(self, + request: Optional[Union[azure_service.CreateAzureNodePoolRequest, dict]] = None, + *, + parent: Optional[str] = None, + azure_node_pool: Optional[azure_resources.AzureNodePool] = None, + azure_node_pool_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool], + attached to a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_create_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + azure_node_pool = gke_multicloud_v1.AzureNodePool() + azure_node_pool.version = "version_value" + azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" + azure_node_pool.subnet_id = "subnet_id_value" + azure_node_pool.autoscaling.min_node_count = 1489 + azure_node_pool.autoscaling.max_node_count = 1491 + azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.CreateAzureNodePoolRequest( + parent="parent_value", + azure_node_pool=azure_node_pool, + azure_node_pool_id="azure_node_pool_id_value", + ) + + # Make the request + operation = client.create_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.CreateAzureNodePoolRequest, dict]): + The request object. Response message for + ``AzureClusters.CreateAzureNodePool`` method. + parent (str): + Required. The + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource where this node pool will be created. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_node_pool (google.cloud.gke_multicloud_v1.types.AzureNodePool): + Required. The specification of the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + to create. + + This corresponds to the ``azure_node_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + azure_node_pool_id (str): + Required. A client provided ID the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource name formatted as + ``projects//locations//azureClusters//azureNodePools/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + This corresponds to the ``azure_node_pool_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AzureNodePool` + An Anthos node pool running on Azure. + + """ + # 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, azure_node_pool, azure_node_pool_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.CreateAzureNodePoolRequest): + request = azure_service.CreateAzureNodePoolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if azure_node_pool is not None: + request.azure_node_pool = azure_node_pool + if azure_node_pool_id is not None: + request.azure_node_pool_id = azure_node_pool_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_azure_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + azure_resources.AzureNodePool, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_azure_node_pool(self, + request: Optional[Union[azure_service.UpdateAzureNodePoolRequest, dict]] = None, + *, + azure_node_pool: Optional[azure_resources.AzureNodePool] = 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, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates an + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. + + .. 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 gke_multicloud_v1 + + def sample_update_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + azure_node_pool = gke_multicloud_v1.AzureNodePool() + azure_node_pool.version = "version_value" + azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" + azure_node_pool.subnet_id = "subnet_id_value" + azure_node_pool.autoscaling.min_node_count = 1489 + azure_node_pool.autoscaling.max_node_count = 1491 + azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.UpdateAzureNodePoolRequest( + azure_node_pool=azure_node_pool, + ) + + # Make the request + operation = client.update_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.UpdateAzureNodePoolRequest, dict]): + The request object. Request message for + ``AzureClusters.UpdateAzureNodePool`` method. + azure_node_pool (google.cloud.gke_multicloud_v1.types.AzureNodePool): + Required. The + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource to update. + + This corresponds to the ``azure_node_pool`` 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 path + must be supplied in this field. The elements of the + repeated paths field can only include these fields from + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]: + + \*. ``annotations``. + + - ``version``. + - ``autoscaling.min_node_count``. + - ``autoscaling.max_node_count``. + - ``config.ssh_config.authorized_key``. + - ``management.auto_repair``. + - ``management``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gke_multicloud_v1.types.AzureNodePool` + An Anthos node pool running on Azure. + + """ + # 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([azure_node_pool, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.UpdateAzureNodePoolRequest): + request = azure_service.UpdateAzureNodePoolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if azure_node_pool is not None: + request.azure_node_pool = azure_node_pool + 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_azure_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_node_pool.name", request.azure_node_pool.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + azure_resources.AzureNodePool, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_azure_node_pool(self, + request: Optional[Union[azure_service.GetAzureNodePoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureNodePool: + r"""Describes a specific + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + 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 gke_multicloud_v1 + + def sample_get_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureNodePoolRequest( + name="name_value", + ) + + # Make the request + response = client.get_azure_node_pool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAzureNodePoolRequest, dict]): + The request object. Request message for ``AzureClusters.GetAzureNodePool`` + method. + name (str): + Required. The name of the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource to describe. + + ``AzureNodePool`` names are formatted as + ``projects//locations//azureClusters//azureNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureNodePool: + An Anthos node pool running on Azure. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureNodePoolRequest): + request = azure_service.GetAzureNodePoolRequest(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_azure_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_azure_node_pools(self, + request: Optional[Union[azure_service.ListAzureNodePoolsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAzureNodePoolsPager: + r"""Lists all + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources on a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + .. 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 gke_multicloud_v1 + + def sample_list_azure_node_pools(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureNodePoolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_node_pools(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest, dict]): + The request object. Request message for ``AzureClusters.ListAzureNodePools`` + method. + parent (str): + Required. The parent ``AzureCluster`` which owns this + collection of + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureNodePoolsPager: + Response message for AzureClusters.ListAzureNodePools + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.ListAzureNodePoolsRequest): + request = azure_service.ListAzureNodePoolsRequest(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_azure_node_pools] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAzureNodePoolsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_azure_node_pool(self, + request: Optional[Union[azure_service.DeleteAzureNodePoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a specific + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + .. 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 gke_multicloud_v1 + + def sample_delete_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureNodePoolRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.DeleteAzureNodePoolRequest, dict]): + The request object. Request message for + ``AzureClusters.DeleteAzureNodePool`` method. + name (str): + Required. The resource name the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + to delete. + + ``AzureNodePool`` names are formatted as + ``projects//locations//azureClusters//azureNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.DeleteAzureNodePoolRequest): + request = azure_service.DeleteAzureNodePoolRequest(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_azure_node_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common_resources.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_azure_open_id_config(self, + request: Optional[Union[azure_service.GetAzureOpenIdConfigRequest, dict]] = None, + *, + azure_cluster: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureOpenIdConfig: + r"""Gets the OIDC discovery document for the cluster. See the + `OpenID Connect Discovery 1.0 + specification `__ + for details. + + .. 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 gke_multicloud_v1 + + def sample_get_azure_open_id_config(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureOpenIdConfigRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = client.get_azure_open_id_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAzureOpenIdConfigRequest, dict]): + The request object. GetAzureOpenIdConfigRequest gets the + OIDC discovery document for the cluster. + See the OpenID Connect Discovery 1.0 + specification for details. + azure_cluster (str): + Required. The AzureCluster, which + owns the OIDC discovery document. + Format: + + projects//locations//azureClusters/ + + This corresponds to the ``azure_cluster`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureOpenIdConfig: + AzureOpenIdConfig is an OIDC + discovery document for the cluster. See + the OpenID Connect Discovery 1.0 + specification for details. + + """ + # 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([azure_cluster]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureOpenIdConfigRequest): + request = azure_service.GetAzureOpenIdConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if azure_cluster is not None: + request.azure_cluster = azure_cluster + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_azure_open_id_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_cluster", request.azure_cluster), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_azure_json_web_keys(self, + request: Optional[Union[azure_service.GetAzureJsonWebKeysRequest, dict]] = None, + *, + azure_cluster: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureJsonWebKeys: + r"""Gets the public component of the cluster signing keys + in JSON Web Key format. + + .. 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 gke_multicloud_v1 + + def sample_get_azure_json_web_keys(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureJsonWebKeysRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = client.get_azure_json_web_keys(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAzureJsonWebKeysRequest, dict]): + The request object. GetAzureJsonWebKeysRequest gets the public component of + the keys used by the cluster to sign token requests. + This will be the jwks_uri for the discover document + returned by getOpenIDConfig. See the OpenID Connect + Discovery 1.0 specification for details. + azure_cluster (str): + Required. The AzureCluster, which owns the JsonWebKeys. + Format: + ``projects//locations//azureClusters/`` + + This corresponds to the ``azure_cluster`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureJsonWebKeys: + AzureJsonWebKeys is a valid JSON Web + Key Set as specififed in RFC 7517. + + """ + # 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([azure_cluster]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureJsonWebKeysRequest): + request = azure_service.GetAzureJsonWebKeysRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if azure_cluster is not None: + request.azure_cluster = azure_cluster + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_azure_json_web_keys] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("azure_cluster", request.azure_cluster), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_azure_server_config(self, + request: Optional[Union[azure_service.GetAzureServerConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> azure_resources.AzureServerConfig: + r"""Returns information, such as supported Azure regions + and Kubernetes versions, on a given Google Cloud + 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 gke_multicloud_v1 + + def sample_get_azure_server_config(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureServerConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_azure_server_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gke_multicloud_v1.types.GetAzureServerConfigRequest, dict]): + The request object. GetAzureServerConfigRequest gets the + server config of GKE cluster on Azure. + name (str): + Required. The name of the + [AzureServerConfig][google.cloud.gkemulticloud.v1.AzureServerConfig] + resource to describe. + + ``AzureServerConfig`` names are formatted as + ``projects//locations//azureServerConfig``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gke_multicloud_v1.types.AzureServerConfig: + AzureServerConfig contains + information about a Google Cloud + location, such as supported Azure + regions and Kubernetes versions. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, azure_service.GetAzureServerConfigRequest): + request = azure_service.GetAzureServerConfigRequest(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_azure_server_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AzureClustersClient": + 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, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def 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, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + 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, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AzureClustersClient", +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/pagers.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/pagers.py new file mode 100644 index 000000000000..bf54373beaf2 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/pagers.py @@ -0,0 +1,445 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.gke_multicloud_v1.types import azure_resources +from google.cloud.gke_multicloud_v1.types import azure_service + + +class ListAzureClientsPager: + """A pager for iterating through ``list_azure_clients`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``azure_clients`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAzureClients`` requests and continue to iterate + through the ``azure_clients`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse` + 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[..., azure_service.ListAzureClientsResponse], + request: azure_service.ListAzureClientsRequest, + response: azure_service.ListAzureClientsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = azure_service.ListAzureClientsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[azure_service.ListAzureClientsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[azure_resources.AzureClient]: + for page in self.pages: + yield from page.azure_clients + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAzureClientsAsyncPager: + """A pager for iterating through ``list_azure_clients`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``azure_clients`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAzureClients`` requests and continue to iterate + through the ``azure_clients`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse` + 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[azure_service.ListAzureClientsResponse]], + request: azure_service.ListAzureClientsRequest, + response: azure_service.ListAzureClientsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = azure_service.ListAzureClientsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[azure_service.ListAzureClientsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[azure_resources.AzureClient]: + async def async_generator(): + async for page in self.pages: + for response in page.azure_clients: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAzureClustersPager: + """A pager for iterating through ``list_azure_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``azure_clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAzureClusters`` requests and continue to iterate + through the ``azure_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse` + 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[..., azure_service.ListAzureClustersResponse], + request: azure_service.ListAzureClustersRequest, + response: azure_service.ListAzureClustersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = azure_service.ListAzureClustersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[azure_service.ListAzureClustersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[azure_resources.AzureCluster]: + for page in self.pages: + yield from page.azure_clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAzureClustersAsyncPager: + """A pager for iterating through ``list_azure_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``azure_clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAzureClusters`` requests and continue to iterate + through the ``azure_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse` + 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[azure_service.ListAzureClustersResponse]], + request: azure_service.ListAzureClustersRequest, + response: azure_service.ListAzureClustersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = azure_service.ListAzureClustersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[azure_service.ListAzureClustersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[azure_resources.AzureCluster]: + async def async_generator(): + async for page in self.pages: + for response in page.azure_clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAzureNodePoolsPager: + """A pager for iterating through ``list_azure_node_pools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``azure_node_pools`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAzureNodePools`` requests and continue to iterate + through the ``azure_node_pools`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse` + 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[..., azure_service.ListAzureNodePoolsResponse], + request: azure_service.ListAzureNodePoolsRequest, + response: azure_service.ListAzureNodePoolsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = azure_service.ListAzureNodePoolsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[azure_service.ListAzureNodePoolsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[azure_resources.AzureNodePool]: + for page in self.pages: + yield from page.azure_node_pools + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAzureNodePoolsAsyncPager: + """A pager for iterating through ``list_azure_node_pools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``azure_node_pools`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAzureNodePools`` requests and continue to iterate + through the ``azure_node_pools`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse` + 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[azure_service.ListAzureNodePoolsResponse]], + request: azure_service.ListAzureNodePoolsRequest, + response: azure_service.ListAzureNodePoolsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest): + The initial request object. + response (google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = azure_service.ListAzureNodePoolsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[azure_service.ListAzureNodePoolsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[azure_resources.AzureNodePool]: + async def async_generator(): + async for page in self.pages: + for response in page.azure_node_pools: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/README.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/README.rst new file mode 100644 index 000000000000..cc9731adcaaa --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AzureClustersTransport` is the ABC for all transports. +- public child `AzureClustersGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AzureClustersGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAzureClustersRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AzureClustersRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/__init__.py new file mode 100644 index 000000000000..d5596ee4b241 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AzureClustersTransport +from .grpc import AzureClustersGrpcTransport +from .grpc_asyncio import AzureClustersGrpcAsyncIOTransport +from .rest import AzureClustersRestTransport +from .rest import AzureClustersRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AzureClustersTransport]] +_transport_registry['grpc'] = AzureClustersGrpcTransport +_transport_registry['grpc_asyncio'] = AzureClustersGrpcAsyncIOTransport +_transport_registry['rest'] = AzureClustersRestTransport + +__all__ = ( + 'AzureClustersTransport', + 'AzureClustersGrpcTransport', + 'AzureClustersGrpcAsyncIOTransport', + 'AzureClustersRestTransport', + 'AzureClustersRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/base.py new file mode 100644 index 000000000000..06191ddf281c --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/base.py @@ -0,0 +1,569 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.gke_multicloud_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.gke_multicloud_v1.types import azure_resources +from google.cloud.gke_multicloud_v1.types import azure_service +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AzureClustersTransport(abc.ABC): + """Abstract transport class for AzureClusters.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'gkemulticloud.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_azure_client: gapic_v1.method.wrap_method( + self.create_azure_client, + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_client: gapic_v1.method.wrap_method( + self.get_azure_client, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_azure_clients: gapic_v1.method.wrap_method( + self.list_azure_clients, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_azure_client: gapic_v1.method.wrap_method( + self.delete_azure_client, + default_timeout=60.0, + client_info=client_info, + ), + self.create_azure_cluster: gapic_v1.method.wrap_method( + self.create_azure_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_azure_cluster: gapic_v1.method.wrap_method( + self.update_azure_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_cluster: gapic_v1.method.wrap_method( + self.get_azure_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_azure_clusters: gapic_v1.method.wrap_method( + self.list_azure_clusters, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_azure_cluster: gapic_v1.method.wrap_method( + self.delete_azure_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.generate_azure_cluster_agent_token: gapic_v1.method.wrap_method( + self.generate_azure_cluster_agent_token, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_azure_access_token: gapic_v1.method.wrap_method( + self.generate_azure_access_token, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_azure_node_pool: gapic_v1.method.wrap_method( + self.create_azure_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.update_azure_node_pool: gapic_v1.method.wrap_method( + self.update_azure_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_node_pool: gapic_v1.method.wrap_method( + self.get_azure_node_pool, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_azure_node_pools: gapic_v1.method.wrap_method( + self.list_azure_node_pools, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_azure_node_pool: gapic_v1.method.wrap_method( + self.delete_azure_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_open_id_config: gapic_v1.method.wrap_method( + self.get_azure_open_id_config, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_json_web_keys: gapic_v1.method.wrap_method( + self.get_azure_json_web_keys, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_server_config: gapic_v1.method.wrap_method( + self.get_azure_server_config, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + 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 create_azure_client(self) -> Callable[ + [azure_service.CreateAzureClientRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_azure_client(self) -> Callable[ + [azure_service.GetAzureClientRequest], + Union[ + azure_resources.AzureClient, + Awaitable[azure_resources.AzureClient] + ]]: + raise NotImplementedError() + + @property + def list_azure_clients(self) -> Callable[ + [azure_service.ListAzureClientsRequest], + Union[ + azure_service.ListAzureClientsResponse, + Awaitable[azure_service.ListAzureClientsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_azure_client(self) -> Callable[ + [azure_service.DeleteAzureClientRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_azure_cluster(self) -> Callable[ + [azure_service.CreateAzureClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_azure_cluster(self) -> Callable[ + [azure_service.UpdateAzureClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_azure_cluster(self) -> Callable[ + [azure_service.GetAzureClusterRequest], + Union[ + azure_resources.AzureCluster, + Awaitable[azure_resources.AzureCluster] + ]]: + raise NotImplementedError() + + @property + def list_azure_clusters(self) -> Callable[ + [azure_service.ListAzureClustersRequest], + Union[ + azure_service.ListAzureClustersResponse, + Awaitable[azure_service.ListAzureClustersResponse] + ]]: + raise NotImplementedError() + + @property + def delete_azure_cluster(self) -> Callable[ + [azure_service.DeleteAzureClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_azure_cluster_agent_token(self) -> Callable[ + [azure_service.GenerateAzureClusterAgentTokenRequest], + Union[ + azure_service.GenerateAzureClusterAgentTokenResponse, + Awaitable[azure_service.GenerateAzureClusterAgentTokenResponse] + ]]: + raise NotImplementedError() + + @property + def generate_azure_access_token(self) -> Callable[ + [azure_service.GenerateAzureAccessTokenRequest], + Union[ + azure_service.GenerateAzureAccessTokenResponse, + Awaitable[azure_service.GenerateAzureAccessTokenResponse] + ]]: + raise NotImplementedError() + + @property + def create_azure_node_pool(self) -> Callable[ + [azure_service.CreateAzureNodePoolRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_azure_node_pool(self) -> Callable[ + [azure_service.UpdateAzureNodePoolRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_azure_node_pool(self) -> Callable[ + [azure_service.GetAzureNodePoolRequest], + Union[ + azure_resources.AzureNodePool, + Awaitable[azure_resources.AzureNodePool] + ]]: + raise NotImplementedError() + + @property + def list_azure_node_pools(self) -> Callable[ + [azure_service.ListAzureNodePoolsRequest], + Union[ + azure_service.ListAzureNodePoolsResponse, + Awaitable[azure_service.ListAzureNodePoolsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_azure_node_pool(self) -> Callable[ + [azure_service.DeleteAzureNodePoolRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_azure_open_id_config(self) -> Callable[ + [azure_service.GetAzureOpenIdConfigRequest], + Union[ + azure_resources.AzureOpenIdConfig, + Awaitable[azure_resources.AzureOpenIdConfig] + ]]: + raise NotImplementedError() + + @property + def get_azure_json_web_keys(self) -> Callable[ + [azure_service.GetAzureJsonWebKeysRequest], + Union[ + azure_resources.AzureJsonWebKeys, + Awaitable[azure_resources.AzureJsonWebKeys] + ]]: + raise NotImplementedError() + + @property + def get_azure_server_config(self) -> Callable[ + [azure_service.GetAzureServerConfigRequest], + Union[ + azure_resources.AzureServerConfig, + Awaitable[azure_resources.AzureServerConfig] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AzureClustersTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc.py new file mode 100644 index 000000000000..1f02eb54c078 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc.py @@ -0,0 +1,981 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +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 +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.gke_multicloud_v1.types import azure_resources +from google.cloud.gke_multicloud_v1.types import azure_service +from google.longrunning import operations_pb2 # type: ignore +from .base import AzureClustersTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AzureClustersGrpcTransport(AzureClustersTransport): + """gRPC backend transport for AzureClusters. + + The AzureClusters API provides a single centrally managed + service to create and manage Anthos clusters that run on Azure + infrastructure. + + 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 = 'gkemulticloud.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'gkemulticloud.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._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_azure_client(self) -> Callable[ + [azure_service.CreateAzureClientRequest], + operations_pb2.Operation]: + r"""Return a callable for the create azure client method over gRPC. + + Creates a new + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource on a given Google Cloud project and region. + + ``AzureClient`` resources hold client authentication information + needed by the Anthos Multicloud API to manage Azure resources on + your Azure subscription on your behalf. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAzureClientRequest], + ~.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_azure_client' not in self._stubs: + self._stubs['create_azure_client'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureClient', + request_serializer=azure_service.CreateAzureClientRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_azure_client'] + + @property + def get_azure_client(self) -> Callable[ + [azure_service.GetAzureClientRequest], + azure_resources.AzureClient]: + r"""Return a callable for the get azure client method over gRPC. + + Describes a specific + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource. + + Returns: + Callable[[~.GetAzureClientRequest], + ~.AzureClient]: + 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_azure_client' not in self._stubs: + self._stubs['get_azure_client'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureClient', + request_serializer=azure_service.GetAzureClientRequest.serialize, + response_deserializer=azure_resources.AzureClient.deserialize, + ) + return self._stubs['get_azure_client'] + + @property + def list_azure_clients(self) -> Callable[ + [azure_service.ListAzureClientsRequest], + azure_service.ListAzureClientsResponse]: + r"""Return a callable for the list azure clients method over gRPC. + + Lists all + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resources on a given Google Cloud project and region. + + Returns: + Callable[[~.ListAzureClientsRequest], + ~.ListAzureClientsResponse]: + 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_azure_clients' not in self._stubs: + self._stubs['list_azure_clients'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureClients', + request_serializer=azure_service.ListAzureClientsRequest.serialize, + response_deserializer=azure_service.ListAzureClientsResponse.deserialize, + ) + return self._stubs['list_azure_clients'] + + @property + def delete_azure_client(self) -> Callable[ + [azure_service.DeleteAzureClientRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete azure client method over gRPC. + + Deletes a specific + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource. + + If the client is used by one or more clusters, deletion will + fail and a ``FAILED_PRECONDITION`` error will be returned. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAzureClientRequest], + ~.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_azure_client' not in self._stubs: + self._stubs['delete_azure_client'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureClient', + request_serializer=azure_service.DeleteAzureClientRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_azure_client'] + + @property + def create_azure_cluster(self) -> Callable[ + [azure_service.CreateAzureClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create azure cluster method over gRPC. + + Creates a new + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAzureClusterRequest], + ~.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_azure_cluster' not in self._stubs: + self._stubs['create_azure_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureCluster', + request_serializer=azure_service.CreateAzureClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_azure_cluster'] + + @property + def update_azure_cluster(self) -> Callable[ + [azure_service.UpdateAzureClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update azure cluster method over gRPC. + + Updates an + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + Returns: + Callable[[~.UpdateAzureClusterRequest], + ~.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_azure_cluster' not in self._stubs: + self._stubs['update_azure_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/UpdateAzureCluster', + request_serializer=azure_service.UpdateAzureClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_azure_cluster'] + + @property + def get_azure_cluster(self) -> Callable[ + [azure_service.GetAzureClusterRequest], + azure_resources.AzureCluster]: + r"""Return a callable for the get azure cluster method over gRPC. + + Describes a specific + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource. + + Returns: + Callable[[~.GetAzureClusterRequest], + ~.AzureCluster]: + 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_azure_cluster' not in self._stubs: + self._stubs['get_azure_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureCluster', + request_serializer=azure_service.GetAzureClusterRequest.serialize, + response_deserializer=azure_resources.AzureCluster.deserialize, + ) + return self._stubs['get_azure_cluster'] + + @property + def list_azure_clusters(self) -> Callable[ + [azure_service.ListAzureClustersRequest], + azure_service.ListAzureClustersResponse]: + r"""Return a callable for the list azure clusters method over gRPC. + + Lists all + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resources on a given Google Cloud project and region. + + Returns: + Callable[[~.ListAzureClustersRequest], + ~.ListAzureClustersResponse]: + 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_azure_clusters' not in self._stubs: + self._stubs['list_azure_clusters'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureClusters', + request_serializer=azure_service.ListAzureClustersRequest.serialize, + response_deserializer=azure_service.ListAzureClustersResponse.deserialize, + ) + return self._stubs['list_azure_clusters'] + + @property + def delete_azure_cluster(self) -> Callable[ + [azure_service.DeleteAzureClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete azure cluster method over gRPC. + + Deletes a specific + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource. + + Fails if the cluster has one or more associated + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAzureClusterRequest], + ~.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_azure_cluster' not in self._stubs: + self._stubs['delete_azure_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureCluster', + request_serializer=azure_service.DeleteAzureClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_azure_cluster'] + + @property + def generate_azure_cluster_agent_token(self) -> Callable[ + [azure_service.GenerateAzureClusterAgentTokenRequest], + azure_service.GenerateAzureClusterAgentTokenResponse]: + r"""Return a callable for the generate azure cluster agent + token method over gRPC. + + Generates an access token for a cluster agent. + + Returns: + Callable[[~.GenerateAzureClusterAgentTokenRequest], + ~.GenerateAzureClusterAgentTokenResponse]: + 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_azure_cluster_agent_token' not in self._stubs: + self._stubs['generate_azure_cluster_agent_token'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GenerateAzureClusterAgentToken', + request_serializer=azure_service.GenerateAzureClusterAgentTokenRequest.serialize, + response_deserializer=azure_service.GenerateAzureClusterAgentTokenResponse.deserialize, + ) + return self._stubs['generate_azure_cluster_agent_token'] + + @property + def generate_azure_access_token(self) -> Callable[ + [azure_service.GenerateAzureAccessTokenRequest], + azure_service.GenerateAzureAccessTokenResponse]: + r"""Return a callable for the generate azure access token method over gRPC. + + Generates a short-lived access token to authenticate to a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource. + + Returns: + Callable[[~.GenerateAzureAccessTokenRequest], + ~.GenerateAzureAccessTokenResponse]: + 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_azure_access_token' not in self._stubs: + self._stubs['generate_azure_access_token'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GenerateAzureAccessToken', + request_serializer=azure_service.GenerateAzureAccessTokenRequest.serialize, + response_deserializer=azure_service.GenerateAzureAccessTokenResponse.deserialize, + ) + return self._stubs['generate_azure_access_token'] + + @property + def create_azure_node_pool(self) -> Callable[ + [azure_service.CreateAzureNodePoolRequest], + operations_pb2.Operation]: + r"""Return a callable for the create azure node pool method over gRPC. + + Creates a new + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool], + attached to a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAzureNodePoolRequest], + ~.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_azure_node_pool' not in self._stubs: + self._stubs['create_azure_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureNodePool', + request_serializer=azure_service.CreateAzureNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_azure_node_pool'] + + @property + def update_azure_node_pool(self) -> Callable[ + [azure_service.UpdateAzureNodePoolRequest], + operations_pb2.Operation]: + r"""Return a callable for the update azure node pool method over gRPC. + + Updates an + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. + + Returns: + Callable[[~.UpdateAzureNodePoolRequest], + ~.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_azure_node_pool' not in self._stubs: + self._stubs['update_azure_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/UpdateAzureNodePool', + request_serializer=azure_service.UpdateAzureNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_azure_node_pool'] + + @property + def get_azure_node_pool(self) -> Callable[ + [azure_service.GetAzureNodePoolRequest], + azure_resources.AzureNodePool]: + r"""Return a callable for the get azure node pool method over gRPC. + + Describes a specific + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource. + + Returns: + Callable[[~.GetAzureNodePoolRequest], + ~.AzureNodePool]: + 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_azure_node_pool' not in self._stubs: + self._stubs['get_azure_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureNodePool', + request_serializer=azure_service.GetAzureNodePoolRequest.serialize, + response_deserializer=azure_resources.AzureNodePool.deserialize, + ) + return self._stubs['get_azure_node_pool'] + + @property + def list_azure_node_pools(self) -> Callable[ + [azure_service.ListAzureNodePoolsRequest], + azure_service.ListAzureNodePoolsResponse]: + r"""Return a callable for the list azure node pools method over gRPC. + + Lists all + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources on a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + Returns: + Callable[[~.ListAzureNodePoolsRequest], + ~.ListAzureNodePoolsResponse]: + 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_azure_node_pools' not in self._stubs: + self._stubs['list_azure_node_pools'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureNodePools', + request_serializer=azure_service.ListAzureNodePoolsRequest.serialize, + response_deserializer=azure_service.ListAzureNodePoolsResponse.deserialize, + ) + return self._stubs['list_azure_node_pools'] + + @property + def delete_azure_node_pool(self) -> Callable[ + [azure_service.DeleteAzureNodePoolRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete azure node pool method over gRPC. + + Deletes a specific + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAzureNodePoolRequest], + ~.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_azure_node_pool' not in self._stubs: + self._stubs['delete_azure_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureNodePool', + request_serializer=azure_service.DeleteAzureNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_azure_node_pool'] + + @property + def get_azure_open_id_config(self) -> Callable[ + [azure_service.GetAzureOpenIdConfigRequest], + azure_resources.AzureOpenIdConfig]: + r"""Return a callable for the get azure open id config method over gRPC. + + Gets the OIDC discovery document for the cluster. See the + `OpenID Connect Discovery 1.0 + specification `__ + for details. + + Returns: + Callable[[~.GetAzureOpenIdConfigRequest], + ~.AzureOpenIdConfig]: + 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_azure_open_id_config' not in self._stubs: + self._stubs['get_azure_open_id_config'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureOpenIdConfig', + request_serializer=azure_service.GetAzureOpenIdConfigRequest.serialize, + response_deserializer=azure_resources.AzureOpenIdConfig.deserialize, + ) + return self._stubs['get_azure_open_id_config'] + + @property + def get_azure_json_web_keys(self) -> Callable[ + [azure_service.GetAzureJsonWebKeysRequest], + azure_resources.AzureJsonWebKeys]: + r"""Return a callable for the get azure json web keys method over gRPC. + + Gets the public component of the cluster signing keys + in JSON Web Key format. + + Returns: + Callable[[~.GetAzureJsonWebKeysRequest], + ~.AzureJsonWebKeys]: + 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_azure_json_web_keys' not in self._stubs: + self._stubs['get_azure_json_web_keys'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureJsonWebKeys', + request_serializer=azure_service.GetAzureJsonWebKeysRequest.serialize, + response_deserializer=azure_resources.AzureJsonWebKeys.deserialize, + ) + return self._stubs['get_azure_json_web_keys'] + + @property + def get_azure_server_config(self) -> Callable[ + [azure_service.GetAzureServerConfigRequest], + azure_resources.AzureServerConfig]: + r"""Return a callable for the get azure server config method over gRPC. + + Returns information, such as supported Azure regions + and Kubernetes versions, on a given Google Cloud + location. + + Returns: + Callable[[~.GetAzureServerConfigRequest], + ~.AzureServerConfig]: + 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_azure_server_config' not in self._stubs: + self._stubs['get_azure_server_config'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureServerConfig', + request_serializer=azure_service.GetAzureServerConfigRequest.serialize, + response_deserializer=azure_resources.AzureServerConfig.deserialize, + ) + return self._stubs['get_azure_server_config'] + + def close(self): + self._logged_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._logged_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._logged_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._logged_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._logged_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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AzureClustersGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc_asyncio.py new file mode 100644 index 000000000000..65631795c139 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc_asyncio.py @@ -0,0 +1,1210 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.gke_multicloud_v1.types import azure_resources +from google.cloud.gke_multicloud_v1.types import azure_service +from google.longrunning import operations_pb2 # type: ignore +from .base import AzureClustersTransport, DEFAULT_CLIENT_INFO +from .grpc import AzureClustersGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AzureClustersGrpcAsyncIOTransport(AzureClustersTransport): + """gRPC AsyncIO backend transport for AzureClusters. + + The AzureClusters API provides a single centrally managed + service to create and manage Anthos clusters that run on Azure + infrastructure. + + 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 = 'gkemulticloud.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'gkemulticloud.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_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._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_azure_client(self) -> Callable[ + [azure_service.CreateAzureClientRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create azure client method over gRPC. + + Creates a new + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource on a given Google Cloud project and region. + + ``AzureClient`` resources hold client authentication information + needed by the Anthos Multicloud API to manage Azure resources on + your Azure subscription on your behalf. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAzureClientRequest], + 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_azure_client' not in self._stubs: + self._stubs['create_azure_client'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureClient', + request_serializer=azure_service.CreateAzureClientRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_azure_client'] + + @property + def get_azure_client(self) -> Callable[ + [azure_service.GetAzureClientRequest], + Awaitable[azure_resources.AzureClient]]: + r"""Return a callable for the get azure client method over gRPC. + + Describes a specific + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource. + + Returns: + Callable[[~.GetAzureClientRequest], + Awaitable[~.AzureClient]]: + 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_azure_client' not in self._stubs: + self._stubs['get_azure_client'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureClient', + request_serializer=azure_service.GetAzureClientRequest.serialize, + response_deserializer=azure_resources.AzureClient.deserialize, + ) + return self._stubs['get_azure_client'] + + @property + def list_azure_clients(self) -> Callable[ + [azure_service.ListAzureClientsRequest], + Awaitable[azure_service.ListAzureClientsResponse]]: + r"""Return a callable for the list azure clients method over gRPC. + + Lists all + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resources on a given Google Cloud project and region. + + Returns: + Callable[[~.ListAzureClientsRequest], + Awaitable[~.ListAzureClientsResponse]]: + 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_azure_clients' not in self._stubs: + self._stubs['list_azure_clients'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureClients', + request_serializer=azure_service.ListAzureClientsRequest.serialize, + response_deserializer=azure_service.ListAzureClientsResponse.deserialize, + ) + return self._stubs['list_azure_clients'] + + @property + def delete_azure_client(self) -> Callable[ + [azure_service.DeleteAzureClientRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete azure client method over gRPC. + + Deletes a specific + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource. + + If the client is used by one or more clusters, deletion will + fail and a ``FAILED_PRECONDITION`` error will be returned. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAzureClientRequest], + 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_azure_client' not in self._stubs: + self._stubs['delete_azure_client'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureClient', + request_serializer=azure_service.DeleteAzureClientRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_azure_client'] + + @property + def create_azure_cluster(self) -> Callable[ + [azure_service.CreateAzureClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create azure cluster method over gRPC. + + Creates a new + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource on a given Google Cloud Platform project and region. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAzureClusterRequest], + 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_azure_cluster' not in self._stubs: + self._stubs['create_azure_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureCluster', + request_serializer=azure_service.CreateAzureClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_azure_cluster'] + + @property + def update_azure_cluster(self) -> Callable[ + [azure_service.UpdateAzureClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update azure cluster method over gRPC. + + Updates an + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + Returns: + Callable[[~.UpdateAzureClusterRequest], + 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_azure_cluster' not in self._stubs: + self._stubs['update_azure_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/UpdateAzureCluster', + request_serializer=azure_service.UpdateAzureClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_azure_cluster'] + + @property + def get_azure_cluster(self) -> Callable[ + [azure_service.GetAzureClusterRequest], + Awaitable[azure_resources.AzureCluster]]: + r"""Return a callable for the get azure cluster method over gRPC. + + Describes a specific + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource. + + Returns: + Callable[[~.GetAzureClusterRequest], + Awaitable[~.AzureCluster]]: + 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_azure_cluster' not in self._stubs: + self._stubs['get_azure_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureCluster', + request_serializer=azure_service.GetAzureClusterRequest.serialize, + response_deserializer=azure_resources.AzureCluster.deserialize, + ) + return self._stubs['get_azure_cluster'] + + @property + def list_azure_clusters(self) -> Callable[ + [azure_service.ListAzureClustersRequest], + Awaitable[azure_service.ListAzureClustersResponse]]: + r"""Return a callable for the list azure clusters method over gRPC. + + Lists all + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resources on a given Google Cloud project and region. + + Returns: + Callable[[~.ListAzureClustersRequest], + Awaitable[~.ListAzureClustersResponse]]: + 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_azure_clusters' not in self._stubs: + self._stubs['list_azure_clusters'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureClusters', + request_serializer=azure_service.ListAzureClustersRequest.serialize, + response_deserializer=azure_service.ListAzureClustersResponse.deserialize, + ) + return self._stubs['list_azure_clusters'] + + @property + def delete_azure_cluster(self) -> Callable[ + [azure_service.DeleteAzureClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete azure cluster method over gRPC. + + Deletes a specific + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource. + + Fails if the cluster has one or more associated + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAzureClusterRequest], + 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_azure_cluster' not in self._stubs: + self._stubs['delete_azure_cluster'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureCluster', + request_serializer=azure_service.DeleteAzureClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_azure_cluster'] + + @property + def generate_azure_cluster_agent_token(self) -> Callable[ + [azure_service.GenerateAzureClusterAgentTokenRequest], + Awaitable[azure_service.GenerateAzureClusterAgentTokenResponse]]: + r"""Return a callable for the generate azure cluster agent + token method over gRPC. + + Generates an access token for a cluster agent. + + Returns: + Callable[[~.GenerateAzureClusterAgentTokenRequest], + Awaitable[~.GenerateAzureClusterAgentTokenResponse]]: + 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_azure_cluster_agent_token' not in self._stubs: + self._stubs['generate_azure_cluster_agent_token'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GenerateAzureClusterAgentToken', + request_serializer=azure_service.GenerateAzureClusterAgentTokenRequest.serialize, + response_deserializer=azure_service.GenerateAzureClusterAgentTokenResponse.deserialize, + ) + return self._stubs['generate_azure_cluster_agent_token'] + + @property + def generate_azure_access_token(self) -> Callable[ + [azure_service.GenerateAzureAccessTokenRequest], + Awaitable[azure_service.GenerateAzureAccessTokenResponse]]: + r"""Return a callable for the generate azure access token method over gRPC. + + Generates a short-lived access token to authenticate to a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource. + + Returns: + Callable[[~.GenerateAzureAccessTokenRequest], + Awaitable[~.GenerateAzureAccessTokenResponse]]: + 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_azure_access_token' not in self._stubs: + self._stubs['generate_azure_access_token'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GenerateAzureAccessToken', + request_serializer=azure_service.GenerateAzureAccessTokenRequest.serialize, + response_deserializer=azure_service.GenerateAzureAccessTokenResponse.deserialize, + ) + return self._stubs['generate_azure_access_token'] + + @property + def create_azure_node_pool(self) -> Callable[ + [azure_service.CreateAzureNodePoolRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create azure node pool method over gRPC. + + Creates a new + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool], + attached to a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.CreateAzureNodePoolRequest], + 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_azure_node_pool' not in self._stubs: + self._stubs['create_azure_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureNodePool', + request_serializer=azure_service.CreateAzureNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_azure_node_pool'] + + @property + def update_azure_node_pool(self) -> Callable[ + [azure_service.UpdateAzureNodePoolRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update azure node pool method over gRPC. + + Updates an + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. + + Returns: + Callable[[~.UpdateAzureNodePoolRequest], + 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_azure_node_pool' not in self._stubs: + self._stubs['update_azure_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/UpdateAzureNodePool', + request_serializer=azure_service.UpdateAzureNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_azure_node_pool'] + + @property + def get_azure_node_pool(self) -> Callable[ + [azure_service.GetAzureNodePoolRequest], + Awaitable[azure_resources.AzureNodePool]]: + r"""Return a callable for the get azure node pool method over gRPC. + + Describes a specific + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource. + + Returns: + Callable[[~.GetAzureNodePoolRequest], + Awaitable[~.AzureNodePool]]: + 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_azure_node_pool' not in self._stubs: + self._stubs['get_azure_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureNodePool', + request_serializer=azure_service.GetAzureNodePoolRequest.serialize, + response_deserializer=azure_resources.AzureNodePool.deserialize, + ) + return self._stubs['get_azure_node_pool'] + + @property + def list_azure_node_pools(self) -> Callable[ + [azure_service.ListAzureNodePoolsRequest], + Awaitable[azure_service.ListAzureNodePoolsResponse]]: + r"""Return a callable for the list azure node pools method over gRPC. + + Lists all + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources on a given + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + Returns: + Callable[[~.ListAzureNodePoolsRequest], + Awaitable[~.ListAzureNodePoolsResponse]]: + 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_azure_node_pools' not in self._stubs: + self._stubs['list_azure_node_pools'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureNodePools', + request_serializer=azure_service.ListAzureNodePoolsRequest.serialize, + response_deserializer=azure_service.ListAzureNodePoolsResponse.deserialize, + ) + return self._stubs['list_azure_node_pools'] + + @property + def delete_azure_node_pool(self) -> Callable[ + [azure_service.DeleteAzureNodePoolRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete azure node pool method over gRPC. + + Deletes a specific + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource. + + If successful, the response contains a newly created + [Operation][google.longrunning.Operation] resource that can be + described to track the status of the operation. + + Returns: + Callable[[~.DeleteAzureNodePoolRequest], + 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_azure_node_pool' not in self._stubs: + self._stubs['delete_azure_node_pool'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureNodePool', + request_serializer=azure_service.DeleteAzureNodePoolRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_azure_node_pool'] + + @property + def get_azure_open_id_config(self) -> Callable[ + [azure_service.GetAzureOpenIdConfigRequest], + Awaitable[azure_resources.AzureOpenIdConfig]]: + r"""Return a callable for the get azure open id config method over gRPC. + + Gets the OIDC discovery document for the cluster. See the + `OpenID Connect Discovery 1.0 + specification `__ + for details. + + Returns: + Callable[[~.GetAzureOpenIdConfigRequest], + Awaitable[~.AzureOpenIdConfig]]: + 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_azure_open_id_config' not in self._stubs: + self._stubs['get_azure_open_id_config'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureOpenIdConfig', + request_serializer=azure_service.GetAzureOpenIdConfigRequest.serialize, + response_deserializer=azure_resources.AzureOpenIdConfig.deserialize, + ) + return self._stubs['get_azure_open_id_config'] + + @property + def get_azure_json_web_keys(self) -> Callable[ + [azure_service.GetAzureJsonWebKeysRequest], + Awaitable[azure_resources.AzureJsonWebKeys]]: + r"""Return a callable for the get azure json web keys method over gRPC. + + Gets the public component of the cluster signing keys + in JSON Web Key format. + + Returns: + Callable[[~.GetAzureJsonWebKeysRequest], + Awaitable[~.AzureJsonWebKeys]]: + 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_azure_json_web_keys' not in self._stubs: + self._stubs['get_azure_json_web_keys'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureJsonWebKeys', + request_serializer=azure_service.GetAzureJsonWebKeysRequest.serialize, + response_deserializer=azure_resources.AzureJsonWebKeys.deserialize, + ) + return self._stubs['get_azure_json_web_keys'] + + @property + def get_azure_server_config(self) -> Callable[ + [azure_service.GetAzureServerConfigRequest], + Awaitable[azure_resources.AzureServerConfig]]: + r"""Return a callable for the get azure server config method over gRPC. + + Returns information, such as supported Azure regions + and Kubernetes versions, on a given Google Cloud + location. + + Returns: + Callable[[~.GetAzureServerConfigRequest], + Awaitable[~.AzureServerConfig]]: + 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_azure_server_config' not in self._stubs: + self._stubs['get_azure_server_config'] = self._logged_channel.unary_unary( + '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureServerConfig', + request_serializer=azure_service.GetAzureServerConfigRequest.serialize, + response_deserializer=azure_resources.AzureServerConfig.deserialize, + ) + return self._stubs['get_azure_server_config'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_azure_client: self._wrap_method( + self.create_azure_client, + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_client: self._wrap_method( + self.get_azure_client, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_azure_clients: self._wrap_method( + self.list_azure_clients, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_azure_client: self._wrap_method( + self.delete_azure_client, + default_timeout=60.0, + client_info=client_info, + ), + self.create_azure_cluster: self._wrap_method( + self.create_azure_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_azure_cluster: self._wrap_method( + self.update_azure_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_cluster: self._wrap_method( + self.get_azure_cluster, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_azure_clusters: self._wrap_method( + self.list_azure_clusters, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_azure_cluster: self._wrap_method( + self.delete_azure_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.generate_azure_cluster_agent_token: self._wrap_method( + self.generate_azure_cluster_agent_token, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_azure_access_token: self._wrap_method( + self.generate_azure_access_token, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_azure_node_pool: self._wrap_method( + self.create_azure_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.update_azure_node_pool: self._wrap_method( + self.update_azure_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_node_pool: self._wrap_method( + self.get_azure_node_pool, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_azure_node_pools: self._wrap_method( + self.list_azure_node_pools, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_azure_node_pool: self._wrap_method( + self.delete_azure_node_pool, + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_open_id_config: self._wrap_method( + self.get_azure_open_id_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_json_web_keys: self._wrap_method( + self.get_azure_json_web_keys, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_azure_server_config: self._wrap_method( + self.get_azure_server_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @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._logged_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._logged_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._logged_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._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'AzureClustersGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest.py new file mode 100644 index 000000000000..7e585427e148 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest.py @@ -0,0 +1,3678 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # 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 gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.gke_multicloud_v1.types import azure_resources +from google.cloud.gke_multicloud_v1.types import azure_service +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseAzureClustersRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class AzureClustersRestInterceptor: + """Interceptor for AzureClusters. + + 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 AzureClustersRestTransport. + + .. code-block:: python + class MyCustomAzureClustersInterceptor(AzureClustersRestInterceptor): + def pre_create_azure_client(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_azure_client(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_azure_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_azure_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_azure_node_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_azure_node_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_azure_client(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_azure_client(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_azure_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_azure_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_azure_node_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_azure_node_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_azure_access_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_azure_access_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_azure_cluster_agent_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_azure_cluster_agent_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_azure_client(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_azure_client(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_azure_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_azure_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_azure_json_web_keys(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_azure_json_web_keys(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_azure_node_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_azure_node_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_azure_open_id_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_azure_open_id_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_azure_server_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_azure_server_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_azure_clients(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_azure_clients(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_azure_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_azure_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_azure_node_pools(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_azure_node_pools(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_azure_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_azure_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_azure_node_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_azure_node_pool(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AzureClustersRestTransport(interceptor=MyCustomAzureClustersInterceptor()) + client = AzureClustersClient(transport=transport) + + + """ + def pre_create_azure_client(self, request: azure_service.CreateAzureClientRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.CreateAzureClientRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_azure_client + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_create_azure_client(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_azure_client + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_create_azure_cluster(self, request: azure_service.CreateAzureClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.CreateAzureClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_azure_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_create_azure_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_azure_cluster + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_create_azure_node_pool(self, request: azure_service.CreateAzureNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.CreateAzureNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_azure_node_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_create_azure_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_azure_node_pool + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_delete_azure_client(self, request: azure_service.DeleteAzureClientRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.DeleteAzureClientRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_azure_client + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_delete_azure_client(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_azure_client + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_delete_azure_cluster(self, request: azure_service.DeleteAzureClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.DeleteAzureClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_azure_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_delete_azure_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_azure_cluster + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_delete_azure_node_pool(self, request: azure_service.DeleteAzureNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.DeleteAzureNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_azure_node_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_delete_azure_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_azure_node_pool + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_generate_azure_access_token(self, request: azure_service.GenerateAzureAccessTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GenerateAzureAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for generate_azure_access_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_generate_azure_access_token(self, response: azure_service.GenerateAzureAccessTokenResponse) -> azure_service.GenerateAzureAccessTokenResponse: + """Post-rpc interceptor for generate_azure_access_token + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_generate_azure_cluster_agent_token(self, request: azure_service.GenerateAzureClusterAgentTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GenerateAzureClusterAgentTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for generate_azure_cluster_agent_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_generate_azure_cluster_agent_token(self, response: azure_service.GenerateAzureClusterAgentTokenResponse) -> azure_service.GenerateAzureClusterAgentTokenResponse: + """Post-rpc interceptor for generate_azure_cluster_agent_token + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_get_azure_client(self, request: azure_service.GetAzureClientRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureClientRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_azure_client + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_get_azure_client(self, response: azure_resources.AzureClient) -> azure_resources.AzureClient: + """Post-rpc interceptor for get_azure_client + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_get_azure_cluster(self, request: azure_service.GetAzureClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_azure_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_get_azure_cluster(self, response: azure_resources.AzureCluster) -> azure_resources.AzureCluster: + """Post-rpc interceptor for get_azure_cluster + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_get_azure_json_web_keys(self, request: azure_service.GetAzureJsonWebKeysRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureJsonWebKeysRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_azure_json_web_keys + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_get_azure_json_web_keys(self, response: azure_resources.AzureJsonWebKeys) -> azure_resources.AzureJsonWebKeys: + """Post-rpc interceptor for get_azure_json_web_keys + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_get_azure_node_pool(self, request: azure_service.GetAzureNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_azure_node_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_get_azure_node_pool(self, response: azure_resources.AzureNodePool) -> azure_resources.AzureNodePool: + """Post-rpc interceptor for get_azure_node_pool + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_get_azure_open_id_config(self, request: azure_service.GetAzureOpenIdConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureOpenIdConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_azure_open_id_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_get_azure_open_id_config(self, response: azure_resources.AzureOpenIdConfig) -> azure_resources.AzureOpenIdConfig: + """Post-rpc interceptor for get_azure_open_id_config + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_get_azure_server_config(self, request: azure_service.GetAzureServerConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureServerConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_azure_server_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_get_azure_server_config(self, response: azure_resources.AzureServerConfig) -> azure_resources.AzureServerConfig: + """Post-rpc interceptor for get_azure_server_config + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_list_azure_clients(self, request: azure_service.ListAzureClientsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.ListAzureClientsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_azure_clients + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_list_azure_clients(self, response: azure_service.ListAzureClientsResponse) -> azure_service.ListAzureClientsResponse: + """Post-rpc interceptor for list_azure_clients + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_list_azure_clusters(self, request: azure_service.ListAzureClustersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.ListAzureClustersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_azure_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_list_azure_clusters(self, response: azure_service.ListAzureClustersResponse) -> azure_service.ListAzureClustersResponse: + """Post-rpc interceptor for list_azure_clusters + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_list_azure_node_pools(self, request: azure_service.ListAzureNodePoolsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.ListAzureNodePoolsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_azure_node_pools + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_list_azure_node_pools(self, response: azure_service.ListAzureNodePoolsResponse) -> azure_service.ListAzureNodePoolsResponse: + """Post-rpc interceptor for list_azure_node_pools + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_update_azure_cluster(self, request: azure_service.UpdateAzureClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.UpdateAzureClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_azure_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_update_azure_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_azure_cluster + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_update_azure_node_pool(self, request: azure_service.UpdateAzureNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.UpdateAzureNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_azure_node_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters server. + """ + return request, metadata + + def post_update_azure_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_azure_node_pool + + Override in a subclass to manipulate the response + after it is returned by the AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters 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 AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters 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 AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters 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 AzureClusters server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AzureClusters 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 AzureClusters server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AzureClustersRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AzureClustersRestInterceptor + + +class AzureClustersRestTransport(_BaseAzureClustersRestTransport): + """REST backend synchronous transport for AzureClusters. + + The AzureClusters API provides a single centrally managed + service to create and manage Anthos clusters that run on Azure + infrastructure. + + 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 = 'gkemulticloud.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[AzureClustersRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + 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 AzureClustersRestInterceptor() + 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 _CreateAzureClient(_BaseAzureClustersRestTransport._BaseCreateAzureClient, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.CreateAzureClient") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: azure_service.CreateAzureClientRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create azure client method over HTTP. + + Args: + request (~.azure_service.CreateAzureClientRequest): + The request object. Request message for ``AzureClusters.CreateAzureClient`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseCreateAzureClient._get_http_options() + + request, metadata = self._interceptor.pre_create_azure_client(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseCreateAzureClient._get_transcoded_request(http_options, request) + + body = _BaseAzureClustersRestTransport._BaseCreateAzureClient._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseCreateAzureClient._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.CreateAzureClient", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "CreateAzureClient", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._CreateAzureClient._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_azure_client(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.create_azure_client", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "CreateAzureClient", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAzureCluster(_BaseAzureClustersRestTransport._BaseCreateAzureCluster, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.CreateAzureCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: azure_service.CreateAzureClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create azure cluster method over HTTP. + + Args: + request (~.azure_service.CreateAzureClusterRequest): + The request object. Request message for ``AzureClusters.CreateAzureCluster`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseCreateAzureCluster._get_http_options() + + request, metadata = self._interceptor.pre_create_azure_cluster(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseCreateAzureCluster._get_transcoded_request(http_options, request) + + body = _BaseAzureClustersRestTransport._BaseCreateAzureCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseCreateAzureCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.CreateAzureCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "CreateAzureCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._CreateAzureCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_azure_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.create_azure_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "CreateAzureCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAzureNodePool(_BaseAzureClustersRestTransport._BaseCreateAzureNodePool, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.CreateAzureNodePool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: azure_service.CreateAzureNodePoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create azure node pool method over HTTP. + + Args: + request (~.azure_service.CreateAzureNodePoolRequest): + The request object. Response message for + ``AzureClusters.CreateAzureNodePool`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseCreateAzureNodePool._get_http_options() + + request, metadata = self._interceptor.pre_create_azure_node_pool(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseCreateAzureNodePool._get_transcoded_request(http_options, request) + + body = _BaseAzureClustersRestTransport._BaseCreateAzureNodePool._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseCreateAzureNodePool._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.CreateAzureNodePool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "CreateAzureNodePool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._CreateAzureNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_azure_node_pool(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.create_azure_node_pool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "CreateAzureNodePool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAzureClient(_BaseAzureClustersRestTransport._BaseDeleteAzureClient, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.DeleteAzureClient") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.DeleteAzureClientRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete azure client method over HTTP. + + Args: + request (~.azure_service.DeleteAzureClientRequest): + The request object. Request message for ``AzureClusters.DeleteAzureClient`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseDeleteAzureClient._get_http_options() + + request, metadata = self._interceptor.pre_delete_azure_client(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseDeleteAzureClient._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseDeleteAzureClient._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.DeleteAzureClient", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "DeleteAzureClient", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._DeleteAzureClient._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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_azure_client(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.delete_azure_client", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "DeleteAzureClient", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAzureCluster(_BaseAzureClustersRestTransport._BaseDeleteAzureCluster, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.DeleteAzureCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.DeleteAzureClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete azure cluster method over HTTP. + + Args: + request (~.azure_service.DeleteAzureClusterRequest): + The request object. Request message for ``AzureClusters.DeleteAzureCluster`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseDeleteAzureCluster._get_http_options() + + request, metadata = self._interceptor.pre_delete_azure_cluster(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseDeleteAzureCluster._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseDeleteAzureCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.DeleteAzureCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "DeleteAzureCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._DeleteAzureCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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_azure_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.delete_azure_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "DeleteAzureCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAzureNodePool(_BaseAzureClustersRestTransport._BaseDeleteAzureNodePool, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.DeleteAzureNodePool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.DeleteAzureNodePoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete azure node pool method over HTTP. + + Args: + request (~.azure_service.DeleteAzureNodePoolRequest): + The request object. Request message for + ``AzureClusters.DeleteAzureNodePool`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseDeleteAzureNodePool._get_http_options() + + request, metadata = self._interceptor.pre_delete_azure_node_pool(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseDeleteAzureNodePool._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseDeleteAzureNodePool._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.DeleteAzureNodePool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "DeleteAzureNodePool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._DeleteAzureNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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_azure_node_pool(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.delete_azure_node_pool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "DeleteAzureNodePool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateAzureAccessToken(_BaseAzureClustersRestTransport._BaseGenerateAzureAccessToken, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.GenerateAzureAccessToken") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.GenerateAzureAccessTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_service.GenerateAzureAccessTokenResponse: + r"""Call the generate azure access + token method over HTTP. + + Args: + request (~.azure_service.GenerateAzureAccessTokenRequest): + The request object. Request message for + ``AzureClusters.GenerateAzureAccessToken`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_service.GenerateAzureAccessTokenResponse: + Response message for + ``AzureClusters.GenerateAzureAccessToken`` method. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseGenerateAzureAccessToken._get_http_options() + + request, metadata = self._interceptor.pre_generate_azure_access_token(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseGenerateAzureAccessToken._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseGenerateAzureAccessToken._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GenerateAzureAccessToken", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GenerateAzureAccessToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._GenerateAzureAccessToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = azure_service.GenerateAzureAccessTokenResponse() + pb_resp = azure_service.GenerateAzureAccessTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_azure_access_token(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_service.GenerateAzureAccessTokenResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.generate_azure_access_token", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GenerateAzureAccessToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateAzureClusterAgentToken(_BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.GenerateAzureClusterAgentToken") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: azure_service.GenerateAzureClusterAgentTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_service.GenerateAzureClusterAgentTokenResponse: + r"""Call the generate azure cluster + agent token method over HTTP. + + Args: + request (~.azure_service.GenerateAzureClusterAgentTokenRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_service.GenerateAzureClusterAgentTokenResponse: + + """ + + http_options = _BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken._get_http_options() + + request, metadata = self._interceptor.pre_generate_azure_cluster_agent_token(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken._get_transcoded_request(http_options, request) + + body = _BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GenerateAzureClusterAgentToken", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GenerateAzureClusterAgentToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._GenerateAzureClusterAgentToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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 = azure_service.GenerateAzureClusterAgentTokenResponse() + pb_resp = azure_service.GenerateAzureClusterAgentTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_azure_cluster_agent_token(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_service.GenerateAzureClusterAgentTokenResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.generate_azure_cluster_agent_token", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GenerateAzureClusterAgentToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAzureClient(_BaseAzureClustersRestTransport._BaseGetAzureClient, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.GetAzureClient") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.GetAzureClientRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_resources.AzureClient: + r"""Call the get azure client method over HTTP. + + Args: + request (~.azure_service.GetAzureClientRequest): + The request object. Request message for ``AzureClusters.GetAzureClient`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_resources.AzureClient: + ``AzureClient`` resources hold client authentication + information needed by the Anthos Multi-Cloud API to + manage Azure resources on your Azure subscription. + + When an + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + is created, an ``AzureClient`` resource needs to be + provided and all operations on Azure resources + associated to that cluster will authenticate to Azure + services using the given client. + + ``AzureClient`` resources are immutable and cannot be + modified upon creation. + + Each ``AzureClient`` resource is bound to a single Azure + Active Directory Application and tenant. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseGetAzureClient._get_http_options() + + request, metadata = self._interceptor.pre_get_azure_client(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureClient._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseGetAzureClient._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureClient", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureClient", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._GetAzureClient._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = azure_resources.AzureClient() + pb_resp = azure_resources.AzureClient.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_azure_client(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_resources.AzureClient.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_client", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureClient", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAzureCluster(_BaseAzureClustersRestTransport._BaseGetAzureCluster, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.GetAzureCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.GetAzureClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_resources.AzureCluster: + r"""Call the get azure cluster method over HTTP. + + Args: + request (~.azure_service.GetAzureClusterRequest): + The request object. Request message for ``AzureClusters.GetAzureCluster`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_resources.AzureCluster: + An Anthos cluster running on Azure. + """ + + http_options = _BaseAzureClustersRestTransport._BaseGetAzureCluster._get_http_options() + + request, metadata = self._interceptor.pre_get_azure_cluster(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureCluster._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseGetAzureCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._GetAzureCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = azure_resources.AzureCluster() + pb_resp = azure_resources.AzureCluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_azure_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_resources.AzureCluster.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAzureJsonWebKeys(_BaseAzureClustersRestTransport._BaseGetAzureJsonWebKeys, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.GetAzureJsonWebKeys") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.GetAzureJsonWebKeysRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_resources.AzureJsonWebKeys: + r"""Call the get azure json web keys method over HTTP. + + Args: + request (~.azure_service.GetAzureJsonWebKeysRequest): + The request object. GetAzureJsonWebKeysRequest gets the public component of + the keys used by the cluster to sign token requests. + This will be the jwks_uri for the discover document + returned by getOpenIDConfig. See the OpenID Connect + Discovery 1.0 specification for details. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_resources.AzureJsonWebKeys: + AzureJsonWebKeys is a valid JSON Web + Key Set as specififed in RFC 7517. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseGetAzureJsonWebKeys._get_http_options() + + request, metadata = self._interceptor.pre_get_azure_json_web_keys(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureJsonWebKeys._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseGetAzureJsonWebKeys._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureJsonWebKeys", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureJsonWebKeys", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._GetAzureJsonWebKeys._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = azure_resources.AzureJsonWebKeys() + pb_resp = azure_resources.AzureJsonWebKeys.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_azure_json_web_keys(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_resources.AzureJsonWebKeys.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_json_web_keys", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureJsonWebKeys", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAzureNodePool(_BaseAzureClustersRestTransport._BaseGetAzureNodePool, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.GetAzureNodePool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.GetAzureNodePoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_resources.AzureNodePool: + r"""Call the get azure node pool method over HTTP. + + Args: + request (~.azure_service.GetAzureNodePoolRequest): + The request object. Request message for ``AzureClusters.GetAzureNodePool`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_resources.AzureNodePool: + An Anthos node pool running on Azure. + """ + + http_options = _BaseAzureClustersRestTransport._BaseGetAzureNodePool._get_http_options() + + request, metadata = self._interceptor.pre_get_azure_node_pool(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureNodePool._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseGetAzureNodePool._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureNodePool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureNodePool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._GetAzureNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = azure_resources.AzureNodePool() + pb_resp = azure_resources.AzureNodePool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_azure_node_pool(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_resources.AzureNodePool.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_node_pool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureNodePool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAzureOpenIdConfig(_BaseAzureClustersRestTransport._BaseGetAzureOpenIdConfig, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.GetAzureOpenIdConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.GetAzureOpenIdConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_resources.AzureOpenIdConfig: + r"""Call the get azure open id config method over HTTP. + + Args: + request (~.azure_service.GetAzureOpenIdConfigRequest): + The request object. GetAzureOpenIdConfigRequest gets the + OIDC discovery document for the cluster. + See the OpenID Connect Discovery 1.0 + specification for details. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_resources.AzureOpenIdConfig: + AzureOpenIdConfig is an OIDC + discovery document for the cluster. See + the OpenID Connect Discovery 1.0 + specification for details. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseGetAzureOpenIdConfig._get_http_options() + + request, metadata = self._interceptor.pre_get_azure_open_id_config(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureOpenIdConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseGetAzureOpenIdConfig._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureOpenIdConfig", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureOpenIdConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._GetAzureOpenIdConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = azure_resources.AzureOpenIdConfig() + pb_resp = azure_resources.AzureOpenIdConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_azure_open_id_config(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_resources.AzureOpenIdConfig.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_open_id_config", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureOpenIdConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAzureServerConfig(_BaseAzureClustersRestTransport._BaseGetAzureServerConfig, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.GetAzureServerConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.GetAzureServerConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_resources.AzureServerConfig: + r"""Call the get azure server config method over HTTP. + + Args: + request (~.azure_service.GetAzureServerConfigRequest): + The request object. GetAzureServerConfigRequest gets the + server config of GKE cluster on Azure. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_resources.AzureServerConfig: + AzureServerConfig contains + information about a Google Cloud + location, such as supported Azure + regions and Kubernetes versions. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseGetAzureServerConfig._get_http_options() + + request, metadata = self._interceptor.pre_get_azure_server_config(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureServerConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseGetAzureServerConfig._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureServerConfig", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureServerConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._GetAzureServerConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = azure_resources.AzureServerConfig() + pb_resp = azure_resources.AzureServerConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_azure_server_config(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_resources.AzureServerConfig.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_server_config", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetAzureServerConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAzureClients(_BaseAzureClustersRestTransport._BaseListAzureClients, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.ListAzureClients") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.ListAzureClientsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_service.ListAzureClientsResponse: + r"""Call the list azure clients method over HTTP. + + Args: + request (~.azure_service.ListAzureClientsRequest): + The request object. Request message for ``AzureClusters.ListAzureClients`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_service.ListAzureClientsResponse: + Response message for ``AzureClusters.ListAzureClients`` + method. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseListAzureClients._get_http_options() + + request, metadata = self._interceptor.pre_list_azure_clients(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseListAzureClients._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseListAzureClients._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.ListAzureClients", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "ListAzureClients", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._ListAzureClients._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = azure_service.ListAzureClientsResponse() + pb_resp = azure_service.ListAzureClientsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_azure_clients(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_service.ListAzureClientsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.list_azure_clients", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "ListAzureClients", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAzureClusters(_BaseAzureClustersRestTransport._BaseListAzureClusters, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.ListAzureClusters") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.ListAzureClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_service.ListAzureClustersResponse: + r"""Call the list azure clusters method over HTTP. + + Args: + request (~.azure_service.ListAzureClustersRequest): + The request object. Request message for ``AzureClusters.ListAzureClusters`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_service.ListAzureClustersResponse: + Response message for ``AzureClusters.ListAzureClusters`` + method. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseListAzureClusters._get_http_options() + + request, metadata = self._interceptor.pre_list_azure_clusters(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseListAzureClusters._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseListAzureClusters._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.ListAzureClusters", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "ListAzureClusters", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._ListAzureClusters._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = azure_service.ListAzureClustersResponse() + pb_resp = azure_service.ListAzureClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_azure_clusters(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_service.ListAzureClustersResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.list_azure_clusters", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "ListAzureClusters", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAzureNodePools(_BaseAzureClustersRestTransport._BaseListAzureNodePools, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.ListAzureNodePools") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: azure_service.ListAzureNodePoolsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> azure_service.ListAzureNodePoolsResponse: + r"""Call the list azure node pools method over HTTP. + + Args: + request (~.azure_service.ListAzureNodePoolsRequest): + The request object. Request message for ``AzureClusters.ListAzureNodePools`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.azure_service.ListAzureNodePoolsResponse: + Response message for + ``AzureClusters.ListAzureNodePools`` method. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseListAzureNodePools._get_http_options() + + request, metadata = self._interceptor.pre_list_azure_node_pools(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseListAzureNodePools._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseListAzureNodePools._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.ListAzureNodePools", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "ListAzureNodePools", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._ListAzureNodePools._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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 = azure_service.ListAzureNodePoolsResponse() + pb_resp = azure_service.ListAzureNodePoolsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_azure_node_pools(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = azure_service.ListAzureNodePoolsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.list_azure_node_pools", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "ListAzureNodePools", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAzureCluster(_BaseAzureClustersRestTransport._BaseUpdateAzureCluster, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.UpdateAzureCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: azure_service.UpdateAzureClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update azure cluster method over HTTP. + + Args: + request (~.azure_service.UpdateAzureClusterRequest): + The request object. Request message for ``AzureClusters.UpdateAzureCluster`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseUpdateAzureCluster._get_http_options() + + request, metadata = self._interceptor.pre_update_azure_cluster(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseUpdateAzureCluster._get_transcoded_request(http_options, request) + + body = _BaseAzureClustersRestTransport._BaseUpdateAzureCluster._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseUpdateAzureCluster._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.UpdateAzureCluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "UpdateAzureCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._UpdateAzureCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_azure_cluster(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.update_azure_cluster", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "UpdateAzureCluster", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAzureNodePool(_BaseAzureClustersRestTransport._BaseUpdateAzureNodePool, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.UpdateAzureNodePool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: azure_service.UpdateAzureNodePoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update azure node pool method over HTTP. + + Args: + request (~.azure_service.UpdateAzureNodePoolRequest): + The request object. Request message for + ``AzureClusters.UpdateAzureNodePool`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAzureClustersRestTransport._BaseUpdateAzureNodePool._get_http_options() + + request, metadata = self._interceptor.pre_update_azure_node_pool(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseUpdateAzureNodePool._get_transcoded_request(http_options, request) + + body = _BaseAzureClustersRestTransport._BaseUpdateAzureNodePool._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseUpdateAzureNodePool._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.UpdateAzureNodePool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "UpdateAzureNodePool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._UpdateAzureNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_azure_node_pool(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.update_azure_node_pool", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "UpdateAzureNodePool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_azure_client(self) -> Callable[ + [azure_service.CreateAzureClientRequest], + 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._CreateAzureClient(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_azure_cluster(self) -> Callable[ + [azure_service.CreateAzureClusterRequest], + 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._CreateAzureCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_azure_node_pool(self) -> Callable[ + [azure_service.CreateAzureNodePoolRequest], + 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._CreateAzureNodePool(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_azure_client(self) -> Callable[ + [azure_service.DeleteAzureClientRequest], + 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._DeleteAzureClient(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_azure_cluster(self) -> Callable[ + [azure_service.DeleteAzureClusterRequest], + 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._DeleteAzureCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_azure_node_pool(self) -> Callable[ + [azure_service.DeleteAzureNodePoolRequest], + 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._DeleteAzureNodePool(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_azure_access_token(self) -> Callable[ + [azure_service.GenerateAzureAccessTokenRequest], + azure_service.GenerateAzureAccessTokenResponse]: + # 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._GenerateAzureAccessToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_azure_cluster_agent_token(self) -> Callable[ + [azure_service.GenerateAzureClusterAgentTokenRequest], + azure_service.GenerateAzureClusterAgentTokenResponse]: + # 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._GenerateAzureClusterAgentToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_azure_client(self) -> Callable[ + [azure_service.GetAzureClientRequest], + azure_resources.AzureClient]: + # 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._GetAzureClient(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_azure_cluster(self) -> Callable[ + [azure_service.GetAzureClusterRequest], + azure_resources.AzureCluster]: + # 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._GetAzureCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_azure_json_web_keys(self) -> Callable[ + [azure_service.GetAzureJsonWebKeysRequest], + azure_resources.AzureJsonWebKeys]: + # 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._GetAzureJsonWebKeys(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_azure_node_pool(self) -> Callable[ + [azure_service.GetAzureNodePoolRequest], + azure_resources.AzureNodePool]: + # 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._GetAzureNodePool(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_azure_open_id_config(self) -> Callable[ + [azure_service.GetAzureOpenIdConfigRequest], + azure_resources.AzureOpenIdConfig]: + # 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._GetAzureOpenIdConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_azure_server_config(self) -> Callable[ + [azure_service.GetAzureServerConfigRequest], + azure_resources.AzureServerConfig]: + # 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._GetAzureServerConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_azure_clients(self) -> Callable[ + [azure_service.ListAzureClientsRequest], + azure_service.ListAzureClientsResponse]: + # 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._ListAzureClients(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_azure_clusters(self) -> Callable[ + [azure_service.ListAzureClustersRequest], + azure_service.ListAzureClustersResponse]: + # 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._ListAzureClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_azure_node_pools(self) -> Callable[ + [azure_service.ListAzureNodePoolsRequest], + azure_service.ListAzureNodePoolsResponse]: + # 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._ListAzureNodePools(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_azure_cluster(self) -> Callable[ + [azure_service.UpdateAzureClusterRequest], + 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._UpdateAzureCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_azure_node_pool(self) -> Callable[ + [azure_service.UpdateAzureNodePoolRequest], + 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._UpdateAzureNodePool(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseAzureClustersRestTransport._BaseCancelOperation, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAzureClustersRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseAzureClustersRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.CancelOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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(_BaseAzureClustersRestTransport._BaseDeleteOperation, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAzureClustersRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # 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(_BaseAzureClustersRestTransport._BaseGetOperation, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseAzureClustersRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseAzureClustersRestTransport._BaseListOperations, AzureClustersRestStub): + def __hash__(self): + return hash("AzureClustersRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseAzureClustersRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseAzureClustersRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAzureClustersRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.ListOperations", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AzureClustersRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkemulticloud_v1.AzureClustersAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AzureClustersRestTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest_base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest_base.py new file mode 100644 index 000000000000..bd10e183c28a --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest_base.py @@ -0,0 +1,942 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import AzureClustersTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.gke_multicloud_v1.types import azure_resources +from google.cloud.gke_multicloud_v1.types import azure_service +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseAzureClustersRestTransport(AzureClustersTransport): + """Base REST backend transport for AzureClusters. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 = 'gkemulticloud.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkemulticloud.googleapis.com'). + credentials (Optional[Any]): 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. + 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 + 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 + ) + + class _BaseCreateAzureClient: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "azureClientId" : "", } + + @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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/azureClients', + 'body': 'azure_client', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.CreateAzureClientRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseCreateAzureClient._get_unset_required_fields(query_params)) + + return query_params + + class _BaseCreateAzureCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "azureClusterId" : "", } + + @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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/azureClusters', + 'body': 'azure_cluster', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.CreateAzureClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseCreateAzureCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseCreateAzureNodePool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "azureNodePoolId" : "", } + + @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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/azureClusters/*}/azureNodePools', + 'body': 'azure_node_pool', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.CreateAzureNodePoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseCreateAzureNodePool._get_unset_required_fields(query_params)) + + return query_params + + class _BaseDeleteAzureClient: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/azureClients/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.DeleteAzureClientRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseDeleteAzureClient._get_unset_required_fields(query_params)) + + return query_params + + class _BaseDeleteAzureCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/azureClusters/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.DeleteAzureClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseDeleteAzureCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseDeleteAzureNodePool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/azureClusters/*/azureNodePools/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.DeleteAzureNodePoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseDeleteAzureNodePool._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGenerateAzureAccessToken: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{azure_cluster=projects/*/locations/*/azureClusters/*}:generateAzureAccessToken', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.GenerateAzureAccessTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseGenerateAzureAccessToken._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGenerateAzureClusterAgentToken: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{azure_cluster=projects/*/locations/*/azureClusters/*}:generateAzureClusterAgentToken', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.GenerateAzureClusterAgentTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAzureClient: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/azureClients/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.GetAzureClientRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureClient._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAzureCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/azureClusters/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.GetAzureClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAzureJsonWebKeys: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{azure_cluster=projects/*/locations/*/azureClusters/*}/jwks', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.GetAzureJsonWebKeysRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureJsonWebKeys._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAzureNodePool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/azureClusters/*/azureNodePools/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.GetAzureNodePoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureNodePool._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAzureOpenIdConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{azure_cluster=projects/*/locations/*/azureClusters/*}/.well-known/openid-configuration', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.GetAzureOpenIdConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureOpenIdConfig._get_unset_required_fields(query_params)) + + return query_params + + class _BaseGetAzureServerConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/azureServerConfig}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.GetAzureServerConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureServerConfig._get_unset_required_fields(query_params)) + + return query_params + + class _BaseListAzureClients: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/azureClients', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.ListAzureClientsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseListAzureClients._get_unset_required_fields(query_params)) + + return query_params + + class _BaseListAzureClusters: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/azureClusters', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.ListAzureClustersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseListAzureClusters._get_unset_required_fields(query_params)) + + return query_params + + class _BaseListAzureNodePools: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/azureClusters/*}/azureNodePools', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.ListAzureNodePoolsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseListAzureNodePools._get_unset_required_fields(query_params)) + + return query_params + + class _BaseUpdateAzureCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{azure_cluster.name=projects/*/locations/*/azureClusters/*}', + 'body': 'azure_cluster', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.UpdateAzureClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseUpdateAzureCluster._get_unset_required_fields(query_params)) + + return query_params + + class _BaseUpdateAzureNodePool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{azure_node_pool.name=projects/*/locations/*/azureClusters/*/azureNodePools/*}', + 'body': 'azure_node_pool', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = azure_service.UpdateAzureNodePoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=False + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseAzureClustersRestTransport._BaseUpdateAzureNodePool._get_unset_required_fields(query_params)) + + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseAzureClustersRestTransport', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/__init__.py new file mode 100644 index 000000000000..8d04ddebf177 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/__init__.py @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .attached_resources import ( + AttachedCluster, + AttachedClusterError, + AttachedClusterGroup, + AttachedClustersAuthorization, + AttachedClusterUser, + AttachedOidcConfig, + AttachedPlatformVersionInfo, + AttachedProxyConfig, + AttachedServerConfig, + KubernetesSecret, +) +from .attached_service import ( + CreateAttachedClusterRequest, + DeleteAttachedClusterRequest, + GenerateAttachedClusterAgentTokenRequest, + GenerateAttachedClusterAgentTokenResponse, + GenerateAttachedClusterInstallManifestRequest, + GenerateAttachedClusterInstallManifestResponse, + GetAttachedClusterRequest, + GetAttachedServerConfigRequest, + ImportAttachedClusterRequest, + ListAttachedClustersRequest, + ListAttachedClustersResponse, + UpdateAttachedClusterRequest, +) +from .aws_resources import ( + AwsAuthorization, + AwsAutoscalingGroupMetricsCollection, + AwsCluster, + AwsClusterError, + AwsClusterGroup, + AwsClusterNetworking, + AwsClusterUser, + AwsConfigEncryption, + AwsControlPlane, + AwsDatabaseEncryption, + AwsInstancePlacement, + AwsJsonWebKeys, + AwsK8sVersionInfo, + AwsNodeConfig, + AwsNodeManagement, + AwsNodePool, + AwsNodePoolAutoscaling, + AwsNodePoolError, + AwsOpenIdConfig, + AwsProxyConfig, + AwsServerConfig, + AwsServicesAuthentication, + AwsSshConfig, + AwsVolumeTemplate, + SpotConfig, + SurgeSettings, + UpdateSettings, +) +from .aws_service import ( + CreateAwsClusterRequest, + CreateAwsNodePoolRequest, + DeleteAwsClusterRequest, + DeleteAwsNodePoolRequest, + GenerateAwsAccessTokenRequest, + GenerateAwsAccessTokenResponse, + GenerateAwsClusterAgentTokenRequest, + GenerateAwsClusterAgentTokenResponse, + GetAwsClusterRequest, + GetAwsJsonWebKeysRequest, + GetAwsNodePoolRequest, + GetAwsOpenIdConfigRequest, + GetAwsServerConfigRequest, + ListAwsClustersRequest, + ListAwsClustersResponse, + ListAwsNodePoolsRequest, + ListAwsNodePoolsResponse, + RollbackAwsNodePoolUpdateRequest, + UpdateAwsClusterRequest, + UpdateAwsNodePoolRequest, +) +from .azure_resources import ( + AzureAuthorization, + AzureClient, + AzureCluster, + AzureClusterError, + AzureClusterGroup, + AzureClusterNetworking, + AzureClusterResources, + AzureClusterUser, + AzureConfigEncryption, + AzureControlPlane, + AzureDatabaseEncryption, + AzureDiskTemplate, + AzureJsonWebKeys, + AzureK8sVersionInfo, + AzureNodeConfig, + AzureNodeManagement, + AzureNodePool, + AzureNodePoolAutoscaling, + AzureNodePoolError, + AzureOpenIdConfig, + AzureProxyConfig, + AzureServerConfig, + AzureServicesAuthentication, + AzureSshConfig, + ReplicaPlacement, +) +from .azure_service import ( + CreateAzureClientRequest, + CreateAzureClusterRequest, + CreateAzureNodePoolRequest, + DeleteAzureClientRequest, + DeleteAzureClusterRequest, + DeleteAzureNodePoolRequest, + GenerateAzureAccessTokenRequest, + GenerateAzureAccessTokenResponse, + GenerateAzureClusterAgentTokenRequest, + GenerateAzureClusterAgentTokenResponse, + GetAzureClientRequest, + GetAzureClusterRequest, + GetAzureJsonWebKeysRequest, + GetAzureNodePoolRequest, + GetAzureOpenIdConfigRequest, + GetAzureServerConfigRequest, + ListAzureClientsRequest, + ListAzureClientsResponse, + ListAzureClustersRequest, + ListAzureClustersResponse, + ListAzureNodePoolsRequest, + ListAzureNodePoolsResponse, + UpdateAzureClusterRequest, + UpdateAzureNodePoolRequest, +) +from .common_resources import ( + BinaryAuthorization, + CloudMonitoringConfig, + Fleet, + Jwk, + LoggingComponentConfig, + LoggingConfig, + ManagedPrometheusConfig, + MaxPodsConstraint, + MonitoringConfig, + NodeKubeletConfig, + NodeTaint, + OperationMetadata, + SecurityPostureConfig, + WorkloadIdentityConfig, +) + +__all__ = ( + 'AttachedCluster', + 'AttachedClusterError', + 'AttachedClusterGroup', + 'AttachedClustersAuthorization', + 'AttachedClusterUser', + 'AttachedOidcConfig', + 'AttachedPlatformVersionInfo', + 'AttachedProxyConfig', + 'AttachedServerConfig', + 'KubernetesSecret', + 'CreateAttachedClusterRequest', + 'DeleteAttachedClusterRequest', + 'GenerateAttachedClusterAgentTokenRequest', + 'GenerateAttachedClusterAgentTokenResponse', + 'GenerateAttachedClusterInstallManifestRequest', + 'GenerateAttachedClusterInstallManifestResponse', + 'GetAttachedClusterRequest', + 'GetAttachedServerConfigRequest', + 'ImportAttachedClusterRequest', + 'ListAttachedClustersRequest', + 'ListAttachedClustersResponse', + 'UpdateAttachedClusterRequest', + 'AwsAuthorization', + 'AwsAutoscalingGroupMetricsCollection', + 'AwsCluster', + 'AwsClusterError', + 'AwsClusterGroup', + 'AwsClusterNetworking', + 'AwsClusterUser', + 'AwsConfigEncryption', + 'AwsControlPlane', + 'AwsDatabaseEncryption', + 'AwsInstancePlacement', + 'AwsJsonWebKeys', + 'AwsK8sVersionInfo', + 'AwsNodeConfig', + 'AwsNodeManagement', + 'AwsNodePool', + 'AwsNodePoolAutoscaling', + 'AwsNodePoolError', + 'AwsOpenIdConfig', + 'AwsProxyConfig', + 'AwsServerConfig', + 'AwsServicesAuthentication', + 'AwsSshConfig', + 'AwsVolumeTemplate', + 'SpotConfig', + 'SurgeSettings', + 'UpdateSettings', + 'CreateAwsClusterRequest', + 'CreateAwsNodePoolRequest', + 'DeleteAwsClusterRequest', + 'DeleteAwsNodePoolRequest', + 'GenerateAwsAccessTokenRequest', + 'GenerateAwsAccessTokenResponse', + 'GenerateAwsClusterAgentTokenRequest', + 'GenerateAwsClusterAgentTokenResponse', + 'GetAwsClusterRequest', + 'GetAwsJsonWebKeysRequest', + 'GetAwsNodePoolRequest', + 'GetAwsOpenIdConfigRequest', + 'GetAwsServerConfigRequest', + 'ListAwsClustersRequest', + 'ListAwsClustersResponse', + 'ListAwsNodePoolsRequest', + 'ListAwsNodePoolsResponse', + 'RollbackAwsNodePoolUpdateRequest', + 'UpdateAwsClusterRequest', + 'UpdateAwsNodePoolRequest', + 'AzureAuthorization', + 'AzureClient', + 'AzureCluster', + 'AzureClusterError', + 'AzureClusterGroup', + 'AzureClusterNetworking', + 'AzureClusterResources', + 'AzureClusterUser', + 'AzureConfigEncryption', + 'AzureControlPlane', + 'AzureDatabaseEncryption', + 'AzureDiskTemplate', + 'AzureJsonWebKeys', + 'AzureK8sVersionInfo', + 'AzureNodeConfig', + 'AzureNodeManagement', + 'AzureNodePool', + 'AzureNodePoolAutoscaling', + 'AzureNodePoolError', + 'AzureOpenIdConfig', + 'AzureProxyConfig', + 'AzureServerConfig', + 'AzureServicesAuthentication', + 'AzureSshConfig', + 'ReplicaPlacement', + 'CreateAzureClientRequest', + 'CreateAzureClusterRequest', + 'CreateAzureNodePoolRequest', + 'DeleteAzureClientRequest', + 'DeleteAzureClusterRequest', + 'DeleteAzureNodePoolRequest', + 'GenerateAzureAccessTokenRequest', + 'GenerateAzureAccessTokenResponse', + 'GenerateAzureClusterAgentTokenRequest', + 'GenerateAzureClusterAgentTokenResponse', + 'GetAzureClientRequest', + 'GetAzureClusterRequest', + 'GetAzureJsonWebKeysRequest', + 'GetAzureNodePoolRequest', + 'GetAzureOpenIdConfigRequest', + 'GetAzureServerConfigRequest', + 'ListAzureClientsRequest', + 'ListAzureClientsResponse', + 'ListAzureClustersRequest', + 'ListAzureClustersResponse', + 'ListAzureNodePoolsRequest', + 'ListAzureNodePoolsResponse', + 'UpdateAzureClusterRequest', + 'UpdateAzureNodePoolRequest', + 'BinaryAuthorization', + 'CloudMonitoringConfig', + 'Fleet', + 'Jwk', + 'LoggingComponentConfig', + 'LoggingConfig', + 'ManagedPrometheusConfig', + 'MaxPodsConstraint', + 'MonitoringConfig', + 'NodeKubeletConfig', + 'NodeTaint', + 'OperationMetadata', + 'SecurityPostureConfig', + 'WorkloadIdentityConfig', +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_resources.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_resources.py new file mode 100644 index 000000000000..b649356e5627 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_resources.py @@ -0,0 +1,505 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.gke_multicloud_v1.types import common_resources +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkemulticloud.v1', + manifest={ + 'AttachedCluster', + 'AttachedClustersAuthorization', + 'AttachedClusterUser', + 'AttachedClusterGroup', + 'AttachedOidcConfig', + 'AttachedServerConfig', + 'AttachedPlatformVersionInfo', + 'AttachedClusterError', + 'AttachedProxyConfig', + 'KubernetesSecret', + }, +) + + +class AttachedCluster(proto.Message): + r"""An Anthos cluster running on customer own infrastructure. + + Attributes: + name (str): + The name of this resource. + + Cluster names are formatted as + ``projects//locations//attachedClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + description (str): + Optional. A human readable description of + this cluster. Cannot be longer than 255 UTF-8 + encoded bytes. + oidc_config (google.cloud.gke_multicloud_v1.types.AttachedOidcConfig): + Required. OpenID Connect (OIDC) configuration + for the cluster. + platform_version (str): + Required. The platform version for the cluster (e.g. + ``1.19.0-gke.1000``). + + You can list all supported versions on a given Google Cloud + region by calling + [GetAttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedServerConfig]. + distribution (str): + Required. The Kubernetes distribution of the underlying + attached cluster. + + Supported values: ["eks", "aks", "generic"]. + cluster_region (str): + Output only. The region where this cluster + runs. + For EKS clusters, this is a AWS region. For AKS + clusters, this is an Azure region. + fleet (google.cloud.gke_multicloud_v1.types.Fleet): + Required. Fleet configuration. + state (google.cloud.gke_multicloud_v1.types.AttachedCluster.State): + Output only. The current state of the + cluster. + uid (str): + Output only. A globally unique identifier for + the cluster. + reconciling (bool): + Output only. If set, there are currently + changes in flight to the cluster. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this cluster + was registered. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this cluster + was last updated. + etag (str): + Allows clients to perform consistent + read-modify-writes through optimistic + concurrency control. + + Can be sent on update and delete requests to + ensure the client has an up-to-date value before + proceeding. + kubernetes_version (str): + Output only. The Kubernetes version of the + cluster. + annotations (MutableMapping[str, str]): + Optional. Annotations on the cluster. + + This field has the same restrictions as Kubernetes + annotations. The total size of all keys and values combined + is limited to 256k. Key can have 2 segments: prefix + (optional) and name (required), separated by a slash (/). + Prefix must be a DNS subdomain. Name must be 63 characters + or less, begin and end with alphanumerics, with dashes (-), + underscores (_), dots (.), and alphanumerics between. + workload_identity_config (google.cloud.gke_multicloud_v1.types.WorkloadIdentityConfig): + Output only. Workload Identity settings. + logging_config (google.cloud.gke_multicloud_v1.types.LoggingConfig): + Optional. Logging configuration for this + cluster. + errors (MutableSequence[google.cloud.gke_multicloud_v1.types.AttachedClusterError]): + Output only. A set of errors found in the + cluster. + authorization (google.cloud.gke_multicloud_v1.types.AttachedClustersAuthorization): + Optional. Configuration related to the + cluster RBAC settings. + monitoring_config (google.cloud.gke_multicloud_v1.types.MonitoringConfig): + Optional. Monitoring configuration for this + cluster. + proxy_config (google.cloud.gke_multicloud_v1.types.AttachedProxyConfig): + Optional. Proxy configuration for outbound + HTTP(S) traffic. + binary_authorization (google.cloud.gke_multicloud_v1.types.BinaryAuthorization): + Optional. Binary Authorization configuration + for this cluster. + security_posture_config (google.cloud.gke_multicloud_v1.types.SecurityPostureConfig): + Optional. Security Posture configuration for + this cluster. + tags (MutableMapping[str, str]): + Optional. Input only. Tag keys/values directly bound to this + resource. + + Tag key must be specified in the format / where the tag + namespace is the ID of the organization or name of the + project that the tag key is defined in. The short name of a + tag key or value can have a maximum length of 256 + characters. The permitted character set for the short name + includes UTF-8 encoded Unicode characters except single + quotes ('), double quotes ("), backslashes (), and forward + slashes (/). + + See + `Tags `__ + for more details on Google Cloud Platform tags. + """ + class State(proto.Enum): + r"""The lifecycle state of the cluster. + + Values: + STATE_UNSPECIFIED (0): + Not set. + PROVISIONING (1): + The PROVISIONING state indicates the cluster + is being registered. + RUNNING (2): + The RUNNING state indicates the cluster has + been register and is fully usable. + RECONCILING (3): + The RECONCILING state indicates that some + work is actively being done on the cluster, such + as upgrading software components. + STOPPING (4): + The STOPPING state indicates the cluster is + being de-registered. + ERROR (5): + The ERROR state indicates the cluster is in a + broken unrecoverable state. + DEGRADED (6): + The DEGRADED state indicates the cluster + requires user action to restore full + functionality. + """ + STATE_UNSPECIFIED = 0 + PROVISIONING = 1 + RUNNING = 2 + RECONCILING = 3 + STOPPING = 4 + ERROR = 5 + DEGRADED = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + oidc_config: 'AttachedOidcConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='AttachedOidcConfig', + ) + platform_version: str = proto.Field( + proto.STRING, + number=4, + ) + distribution: str = proto.Field( + proto.STRING, + number=16, + ) + cluster_region: str = proto.Field( + proto.STRING, + number=22, + ) + fleet: common_resources.Fleet = proto.Field( + proto.MESSAGE, + number=5, + message=common_resources.Fleet, + ) + state: State = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + uid: str = proto.Field( + proto.STRING, + number=7, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=8, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=11, + ) + kubernetes_version: str = proto.Field( + proto.STRING, + number=12, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + workload_identity_config: common_resources.WorkloadIdentityConfig = proto.Field( + proto.MESSAGE, + number=14, + message=common_resources.WorkloadIdentityConfig, + ) + logging_config: common_resources.LoggingConfig = proto.Field( + proto.MESSAGE, + number=15, + message=common_resources.LoggingConfig, + ) + errors: MutableSequence['AttachedClusterError'] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message='AttachedClusterError', + ) + authorization: 'AttachedClustersAuthorization' = proto.Field( + proto.MESSAGE, + number=21, + message='AttachedClustersAuthorization', + ) + monitoring_config: common_resources.MonitoringConfig = proto.Field( + proto.MESSAGE, + number=23, + message=common_resources.MonitoringConfig, + ) + proxy_config: 'AttachedProxyConfig' = proto.Field( + proto.MESSAGE, + number=24, + message='AttachedProxyConfig', + ) + binary_authorization: common_resources.BinaryAuthorization = proto.Field( + proto.MESSAGE, + number=25, + message=common_resources.BinaryAuthorization, + ) + security_posture_config: common_resources.SecurityPostureConfig = proto.Field( + proto.MESSAGE, + number=26, + message=common_resources.SecurityPostureConfig, + ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=27, + ) + + +class AttachedClustersAuthorization(proto.Message): + r"""Configuration related to the cluster RBAC settings. + + Attributes: + admin_users (MutableSequence[google.cloud.gke_multicloud_v1.types.AttachedClusterUser]): + Optional. Users that can perform operations as a cluster + admin. A managed ClusterRoleBinding will be created to grant + the ``cluster-admin`` ClusterRole to the users. Up to ten + admin users can be provided. + + For more info on RBAC, see + https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles + admin_groups (MutableSequence[google.cloud.gke_multicloud_v1.types.AttachedClusterGroup]): + Optional. Groups of users that can perform operations as a + cluster admin. A managed ClusterRoleBinding will be created + to grant the ``cluster-admin`` ClusterRole to the groups. Up + to ten admin groups can be provided. + + For more info on RBAC, see + https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles + """ + + admin_users: MutableSequence['AttachedClusterUser'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AttachedClusterUser', + ) + admin_groups: MutableSequence['AttachedClusterGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AttachedClusterGroup', + ) + + +class AttachedClusterUser(proto.Message): + r"""Identities of a user-type subject for Attached clusters. + + Attributes: + username (str): + Required. The name of the user, e.g. + ``my-gcp-id@gmail.com``. + """ + + username: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AttachedClusterGroup(proto.Message): + r"""Identities of a group-type subject for Attached clusters. + + Attributes: + group (str): + Required. The name of the group, e.g. + ``my-group@domain.com``. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AttachedOidcConfig(proto.Message): + r"""OIDC discovery information of the target cluster. + + Kubernetes Service Account (KSA) tokens are JWT tokens signed by the + cluster API server. This fields indicates how Google Cloud Platform + services validate KSA tokens in order to allow system workloads + (such as GKE Connect and telemetry agents) to authenticate back to + Google Cloud Platform. + + Both clusters with public and private issuer URLs are supported. + Clusters with public issuers only need to specify the ``issuer_url`` + field while clusters with private issuers need to provide both + ``issuer_url`` and ``oidc_jwks``. + + Attributes: + issuer_url (str): + A JSON Web Token (JWT) issuer URI. ``issuer`` must start + with ``https://``. + jwks (bytes): + Optional. OIDC verification keys in JWKS + format (RFC 7517). It contains a list of OIDC + verification keys that can be used to verify + OIDC JWTs. + + This field is required for cluster that doesn't + have a publicly available discovery endpoint. + When provided, it will be directly used to + verify the OIDC JWT asserted by the IDP. + """ + + issuer_url: str = proto.Field( + proto.STRING, + number=1, + ) + jwks: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class AttachedServerConfig(proto.Message): + r"""AttachedServerConfig provides information about supported + Kubernetes versions + + Attributes: + name (str): + The resource name of the config. + valid_versions (MutableSequence[google.cloud.gke_multicloud_v1.types.AttachedPlatformVersionInfo]): + List of valid platform versions. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + valid_versions: MutableSequence['AttachedPlatformVersionInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AttachedPlatformVersionInfo', + ) + + +class AttachedPlatformVersionInfo(proto.Message): + r"""Information about a supported Attached Clusters platform + version. + + Attributes: + version (str): + Platform version name. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AttachedClusterError(proto.Message): + r"""AttachedClusterError describes errors found on attached + clusters. + + Attributes: + message (str): + Human-friendly description of the error. + """ + + message: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AttachedProxyConfig(proto.Message): + r"""Details of a proxy config. + + Attributes: + kubernetes_secret (google.cloud.gke_multicloud_v1.types.KubernetesSecret): + The Kubernetes Secret resource that contains + the HTTP(S) proxy configuration. The secret must + be a JSON encoded proxy configuration as + described in + https://cloud.google.com/kubernetes-engine/multi-cloud/docs/attached/eks/how-to/use-a-proxy#configure-proxy-support + for EKS clusters and + https://cloud.google.com/kubernetes-engine/multi-cloud/docs/attached/aks/how-to/use-a-proxy#configure-proxy-support + for AKS clusters. + """ + + kubernetes_secret: 'KubernetesSecret' = proto.Field( + proto.MESSAGE, + number=1, + message='KubernetesSecret', + ) + + +class KubernetesSecret(proto.Message): + r"""Information about a Kubernetes Secret + + Attributes: + name (str): + Name of the kubernetes secret. + namespace (str): + Namespace in which the kubernetes secret is + stored. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + namespace: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_service.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_service.py new file mode 100644 index 000000000000..c70df2d38a21 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_service.py @@ -0,0 +1,574 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.gke_multicloud_v1.types import attached_resources +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkemulticloud.v1', + manifest={ + 'GenerateAttachedClusterInstallManifestRequest', + 'GenerateAttachedClusterInstallManifestResponse', + 'CreateAttachedClusterRequest', + 'ImportAttachedClusterRequest', + 'UpdateAttachedClusterRequest', + 'GetAttachedClusterRequest', + 'ListAttachedClustersRequest', + 'ListAttachedClustersResponse', + 'DeleteAttachedClusterRequest', + 'GetAttachedServerConfigRequest', + 'GenerateAttachedClusterAgentTokenRequest', + 'GenerateAttachedClusterAgentTokenResponse', + }, +) + + +class GenerateAttachedClusterInstallManifestRequest(proto.Message): + r"""Request message for + ``AttachedClusters.GenerateAttachedClusterInstallManifest`` method. + + Attributes: + parent (str): + Required. The parent location where this + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + attached_cluster_id (str): + Required. A client provided ID of the resource. Must be + unique within the parent resource. + + The provided ID will be part of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource name formatted as + ``projects//locations//attachedClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + + When generating an install manifest for importing an + existing Membership resource, the attached_cluster_id field + must be the Membership id. + + Membership names are formatted as + ``projects//locations//memberships/``. + platform_version (str): + Required. The platform version for the cluster (e.g. + ``1.19.0-gke.1000``). + + You can list all supported versions on a given Google Cloud + region by calling + [GetAttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedServerConfig]. + proxy_config (google.cloud.gke_multicloud_v1.types.AttachedProxyConfig): + Optional. Proxy configuration for outbound + HTTP(S) traffic. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + attached_cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + platform_version: str = proto.Field( + proto.STRING, + number=3, + ) + proxy_config: attached_resources.AttachedProxyConfig = proto.Field( + proto.MESSAGE, + number=4, + message=attached_resources.AttachedProxyConfig, + ) + + +class GenerateAttachedClusterInstallManifestResponse(proto.Message): + r"""Response message for + ``AttachedClusters.GenerateAttachedClusterInstallManifest`` method. + + Attributes: + manifest (str): + A set of Kubernetes resources (in YAML + format) to be applied to the cluster to be + attached. + """ + + manifest: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAttachedClusterRequest(proto.Message): + r"""Request message for ``AttachedClusters.CreateAttachedCluster`` + method. + + Attributes: + parent (str): + Required. The parent location where this + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + attached_cluster (google.cloud.gke_multicloud_v1.types.AttachedCluster): + Required. The specification of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + to create. + attached_cluster_id (str): + Required. A client provided ID the resource. Must be unique + within the parent resource. + + The provided ID will be part of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource name formatted as + ``projects//locations//attachedClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + validate_only (bool): + If set, only validate the request, but do not + actually create the cluster. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + attached_cluster: attached_resources.AttachedCluster = proto.Field( + proto.MESSAGE, + number=2, + message=attached_resources.AttachedCluster, + ) + attached_cluster_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ImportAttachedClusterRequest(proto.Message): + r"""Request message for ``AttachedClusters.ImportAttachedCluster`` + method. + + Attributes: + parent (str): + Required. The parent location where this + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + validate_only (bool): + If set, only validate the request, but do not + actually import the cluster. + fleet_membership (str): + Required. The name of the fleet membership + resource to import. + platform_version (str): + Required. The platform version for the cluster (e.g. + ``1.19.0-gke.1000``). + + You can list all supported versions on a given Google Cloud + region by calling + [GetAttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedServerConfig]. + distribution (str): + Required. The Kubernetes distribution of the underlying + attached cluster. + + Supported values: ["eks", "aks", "generic"]. + proxy_config (google.cloud.gke_multicloud_v1.types.AttachedProxyConfig): + Optional. Proxy configuration for outbound + HTTP(S) traffic. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + fleet_membership: str = proto.Field( + proto.STRING, + number=3, + ) + platform_version: str = proto.Field( + proto.STRING, + number=4, + ) + distribution: str = proto.Field( + proto.STRING, + number=5, + ) + proxy_config: attached_resources.AttachedProxyConfig = proto.Field( + proto.MESSAGE, + number=6, + message=attached_resources.AttachedProxyConfig, + ) + + +class UpdateAttachedClusterRequest(proto.Message): + r"""Request message for ``AttachedClusters.UpdateAttachedCluster`` + method. + + Attributes: + attached_cluster (google.cloud.gke_multicloud_v1.types.AttachedCluster): + Required. The + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource to update. + validate_only (bool): + If set, only validate the request, but do not + actually update the cluster. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. At least one path must + be supplied in this field. The elements of the repeated + paths field can only include these fields from + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]: + + - ``annotations``. + - ``authorization.admin_groups``. + - ``authorization.admin_users``. + - ``binary_authorization.evaluation_mode``. + - ``description``. + - ``logging_config.component_config.enable_components``. + - ``monitoring_config.managed_prometheus_config.enabled``. + - ``platform_version``. + - ``proxy_config.kubernetes_secret.name``. + - ``proxy_config.kubernetes_secret.namespace``. + - ``security_posture_config.vulnerability_mode`` + - ``monitoring_config.cloud_monitoring_config.enabled`` + """ + + attached_cluster: attached_resources.AttachedCluster = proto.Field( + proto.MESSAGE, + number=1, + message=attached_resources.AttachedCluster, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class GetAttachedClusterRequest(proto.Message): + r"""Request message for ``AttachedClusters.GetAttachedCluster`` method. + + Attributes: + name (str): + Required. The name of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource to describe. + + ``AttachedCluster`` names are formatted as + ``projects//locations//attachedClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAttachedClustersRequest(proto.Message): + r"""Request message for ``AttachedClusters.ListAttachedClusters`` + method. + + Attributes: + parent (str): + Required. The parent location which owns this collection of + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + page_size (int): + The maximum number of items to return. + + If not specified, a default value of 50 will be used by the + service. Regardless of the pageSize value, the response can + include a partial list and a caller should only rely on + response's + [nextPageToken][google.cloud.gkemulticloud.v1.ListAttachedClustersResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + The ``nextPageToken`` value returned from a previous + [attachedClusters.list][google.cloud.gkemulticloud.v1.AttachedClusters.ListAttachedClusters] + request, if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAttachedClustersResponse(proto.Message): + r"""Response message for ``AttachedClusters.ListAttachedClusters`` + method. + + Attributes: + attached_clusters (MutableSequence[google.cloud.gke_multicloud_v1.types.AttachedCluster]): + A list of + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resources in the specified Google Cloud Platform project and + region region. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + attached_clusters: MutableSequence[attached_resources.AttachedCluster] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=attached_resources.AttachedCluster, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteAttachedClusterRequest(proto.Message): + r"""Request message for ``AttachedClusters.DeleteAttachedCluster`` + method. + + Attributes: + name (str): + Required. The resource name the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + to delete. + + ``AttachedCluster`` names are formatted as + ``projects//locations//attachedClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + validate_only (bool): + If set, only validate the request, but do not + actually delete the resource. + allow_missing (bool): + If set to true, and the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource is not found, the request will succeed but no + action will be taken on the server and a completed + [Operation][google.longrunning.Operation] will be returned. + + Useful for idempotent deletion. + ignore_errors (bool): + If set to true, the deletion of + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + resource will succeed even if errors occur during deleting + in cluster resources. Using this parameter may result in + orphaned resources in the cluster. + etag (str): + The current etag of the + [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. + + Allows clients to perform deletions through optimistic + concurrency control. + + If the provided etag does not match the current etag of the + cluster, the request will fail and an ABORTED error will be + returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + ignore_errors: bool = proto.Field( + proto.BOOL, + number=5, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetAttachedServerConfigRequest(proto.Message): + r"""GetAttachedServerConfigRequest gets the server config for + attached clusters. + + Attributes: + name (str): + Required. The name of the + [AttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedServerConfig] + resource to describe. + + ``AttachedServerConfig`` names are formatted as + ``projects//locations//attachedServerConfig``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateAttachedClusterAgentTokenRequest(proto.Message): + r""" + + Attributes: + attached_cluster (str): + Required. + subject_token (str): + Required. + subject_token_type (str): + Required. + version (str): + Required. + grant_type (str): + Optional. + audience (str): + Optional. + scope (str): + Optional. + requested_token_type (str): + Optional. + options (str): + Optional. + """ + + attached_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + subject_token: str = proto.Field( + proto.STRING, + number=2, + ) + subject_token_type: str = proto.Field( + proto.STRING, + number=3, + ) + version: str = proto.Field( + proto.STRING, + number=4, + ) + grant_type: str = proto.Field( + proto.STRING, + number=6, + ) + audience: str = proto.Field( + proto.STRING, + number=7, + ) + scope: str = proto.Field( + proto.STRING, + number=8, + ) + requested_token_type: str = proto.Field( + proto.STRING, + number=9, + ) + options: str = proto.Field( + proto.STRING, + number=10, + ) + + +class GenerateAttachedClusterAgentTokenResponse(proto.Message): + r""" + + Attributes: + access_token (str): + + expires_in (int): + + token_type (str): + + """ + + access_token: str = proto.Field( + proto.STRING, + number=1, + ) + expires_in: int = proto.Field( + proto.INT32, + number=2, + ) + token_type: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_resources.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_resources.py new file mode 100644 index 000000000000..16a3cf1e51b0 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_resources.py @@ -0,0 +1,1424 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.gke_multicloud_v1.types import common_resources +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkemulticloud.v1', + manifest={ + 'AwsCluster', + 'AwsControlPlane', + 'AwsServicesAuthentication', + 'AwsAuthorization', + 'AwsClusterUser', + 'AwsClusterGroup', + 'AwsDatabaseEncryption', + 'AwsVolumeTemplate', + 'AwsClusterNetworking', + 'AwsNodePool', + 'UpdateSettings', + 'SurgeSettings', + 'AwsNodeManagement', + 'AwsNodeConfig', + 'AwsNodePoolAutoscaling', + 'AwsOpenIdConfig', + 'AwsJsonWebKeys', + 'AwsServerConfig', + 'AwsK8sVersionInfo', + 'AwsSshConfig', + 'AwsProxyConfig', + 'AwsConfigEncryption', + 'AwsInstancePlacement', + 'AwsAutoscalingGroupMetricsCollection', + 'SpotConfig', + 'AwsClusterError', + 'AwsNodePoolError', + }, +) + + +class AwsCluster(proto.Message): + r"""An Anthos cluster running on AWS. + + Attributes: + name (str): + The name of this resource. + + Cluster names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + description (str): + Optional. A human readable description of + this cluster. Cannot be longer than 255 UTF-8 + encoded bytes. + networking (google.cloud.gke_multicloud_v1.types.AwsClusterNetworking): + Required. Cluster-wide networking + configuration. + aws_region (str): + Required. The AWS region where the cluster runs. + + Each Google Cloud region supports a subset of nearby AWS + regions. You can call + [GetAwsServerConfig][google.cloud.gkemulticloud.v1.AwsClusters.GetAwsServerConfig] + to list all supported AWS regions within a given Google + Cloud region. + control_plane (google.cloud.gke_multicloud_v1.types.AwsControlPlane): + Required. Configuration related to the + cluster control plane. + authorization (google.cloud.gke_multicloud_v1.types.AwsAuthorization): + Required. Configuration related to the + cluster RBAC settings. + state (google.cloud.gke_multicloud_v1.types.AwsCluster.State): + Output only. The current state of the + cluster. + endpoint (str): + Output only. The endpoint of the cluster's + API server. + uid (str): + Output only. A globally unique identifier for + the cluster. + reconciling (bool): + Output only. If set, there are currently + changes in flight to the cluster. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this cluster + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this cluster + was last updated. + etag (str): + Allows clients to perform consistent + read-modify-writes through optimistic + concurrency control. + + Can be sent on update and delete requests to + ensure the client has an up-to-date value before + proceeding. + annotations (MutableMapping[str, str]): + Optional. Annotations on the cluster. + + This field has the same restrictions as Kubernetes + annotations. The total size of all keys and values combined + is limited to 256k. Key can have 2 segments: prefix + (optional) and name (required), separated by a slash (/). + Prefix must be a DNS subdomain. Name must be 63 characters + or less, begin and end with alphanumerics, with dashes (-), + underscores (_), dots (.), and alphanumerics between. + workload_identity_config (google.cloud.gke_multicloud_v1.types.WorkloadIdentityConfig): + Output only. Workload Identity settings. + cluster_ca_certificate (str): + Output only. PEM encoded x509 certificate of + the cluster root of trust. + fleet (google.cloud.gke_multicloud_v1.types.Fleet): + Required. Fleet configuration. + logging_config (google.cloud.gke_multicloud_v1.types.LoggingConfig): + Optional. Logging configuration for this + cluster. + errors (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsClusterError]): + Output only. A set of errors found in the + cluster. + monitoring_config (google.cloud.gke_multicloud_v1.types.MonitoringConfig): + Optional. Monitoring configuration for this + cluster. + binary_authorization (google.cloud.gke_multicloud_v1.types.BinaryAuthorization): + Optional. Binary Authorization configuration + for this cluster. + """ + class State(proto.Enum): + r"""The lifecycle state of the cluster. + + Values: + STATE_UNSPECIFIED (0): + Not set. + PROVISIONING (1): + The PROVISIONING state indicates the cluster + is being created. + RUNNING (2): + The RUNNING state indicates the cluster has + been created and is fully usable. + RECONCILING (3): + The RECONCILING state indicates that some + work is actively being done on the cluster, such + as upgrading the control plane replicas. + STOPPING (4): + The STOPPING state indicates the cluster is + being deleted. + ERROR (5): + The ERROR state indicates the cluster is in a + broken unrecoverable state. + DEGRADED (6): + The DEGRADED state indicates the cluster + requires user action to restore full + functionality. + """ + STATE_UNSPECIFIED = 0 + PROVISIONING = 1 + RUNNING = 2 + RECONCILING = 3 + STOPPING = 4 + ERROR = 5 + DEGRADED = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + networking: 'AwsClusterNetworking' = proto.Field( + proto.MESSAGE, + number=3, + message='AwsClusterNetworking', + ) + aws_region: str = proto.Field( + proto.STRING, + number=4, + ) + control_plane: 'AwsControlPlane' = proto.Field( + proto.MESSAGE, + number=5, + message='AwsControlPlane', + ) + authorization: 'AwsAuthorization' = proto.Field( + proto.MESSAGE, + number=15, + message='AwsAuthorization', + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + endpoint: str = proto.Field( + proto.STRING, + number=8, + ) + uid: str = proto.Field( + proto.STRING, + number=9, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=10, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=13, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + workload_identity_config: common_resources.WorkloadIdentityConfig = proto.Field( + proto.MESSAGE, + number=16, + message=common_resources.WorkloadIdentityConfig, + ) + cluster_ca_certificate: str = proto.Field( + proto.STRING, + number=17, + ) + fleet: common_resources.Fleet = proto.Field( + proto.MESSAGE, + number=18, + message=common_resources.Fleet, + ) + logging_config: common_resources.LoggingConfig = proto.Field( + proto.MESSAGE, + number=19, + message=common_resources.LoggingConfig, + ) + errors: MutableSequence['AwsClusterError'] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message='AwsClusterError', + ) + monitoring_config: common_resources.MonitoringConfig = proto.Field( + proto.MESSAGE, + number=21, + message=common_resources.MonitoringConfig, + ) + binary_authorization: common_resources.BinaryAuthorization = proto.Field( + proto.MESSAGE, + number=22, + message=common_resources.BinaryAuthorization, + ) + + +class AwsControlPlane(proto.Message): + r"""ControlPlane defines common parameters between control plane + nodes. + + Attributes: + version (str): + Required. The Kubernetes version to run on control plane + replicas (e.g. ``1.19.10-gke.1000``). + + You can list all supported versions on a given Google Cloud + region by calling + [GetAwsServerConfig][google.cloud.gkemulticloud.v1.AwsClusters.GetAwsServerConfig]. + instance_type (str): + Optional. The AWS instance type. + + When unspecified, it uses a default based on the + cluster's version. + ssh_config (google.cloud.gke_multicloud_v1.types.AwsSshConfig): + Optional. SSH configuration for how to access + the underlying control plane machines. + subnet_ids (MutableSequence[str]): + Required. The list of subnets where control + plane replicas will run. A replica will be + provisioned on each subnet and up to three + values can be provided. + Each subnet must be in a different AWS + Availability Zone (AZ). + security_group_ids (MutableSequence[str]): + Optional. The IDs of additional security + groups to add to control plane replicas. The + Anthos Multi-Cloud API will automatically create + and manage security groups with the minimum + rules needed for a functioning cluster. + iam_instance_profile (str): + Required. The name or ARN of the AWS IAM + instance profile to assign to each control plane + replica. + root_volume (google.cloud.gke_multicloud_v1.types.AwsVolumeTemplate): + Optional. Configuration related to the root + volume provisioned for each control plane + replica. + + Volumes will be provisioned in the availability + zone associated with the corresponding subnet. + + When unspecified, it defaults to 32 GiB with the + GP2 volume type. + main_volume (google.cloud.gke_multicloud_v1.types.AwsVolumeTemplate): + Optional. Configuration related to the main + volume provisioned for each control plane + replica. The main volume is in charge of storing + all of the cluster's etcd state. + + Volumes will be provisioned in the availability + zone associated with the corresponding subnet. + + When unspecified, it defaults to 8 GiB with the + GP2 volume type. + database_encryption (google.cloud.gke_multicloud_v1.types.AwsDatabaseEncryption): + Required. The ARN of the AWS KMS key used to + encrypt cluster secrets. + tags (MutableMapping[str, str]): + Optional. A set of AWS resource tags to propagate to all + underlying managed AWS resources. + + Specify at most 50 pairs containing alphanumerics, spaces, + and symbols (.+-=_:@/). Keys can be up to 127 Unicode + characters. Values can be up to 255 Unicode characters. + aws_services_authentication (google.cloud.gke_multicloud_v1.types.AwsServicesAuthentication): + Required. Authentication configuration for + management of AWS resources. + proxy_config (google.cloud.gke_multicloud_v1.types.AwsProxyConfig): + Optional. Proxy configuration for outbound + HTTP(S) traffic. + config_encryption (google.cloud.gke_multicloud_v1.types.AwsConfigEncryption): + Required. Config encryption for user data. + instance_placement (google.cloud.gke_multicloud_v1.types.AwsInstancePlacement): + Optional. The placement to use on control + plane instances. When unspecified, the VPC's + default tenancy will be used. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + instance_type: str = proto.Field( + proto.STRING, + number=2, + ) + ssh_config: 'AwsSshConfig' = proto.Field( + proto.MESSAGE, + number=14, + message='AwsSshConfig', + ) + subnet_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + security_group_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + iam_instance_profile: str = proto.Field( + proto.STRING, + number=7, + ) + root_volume: 'AwsVolumeTemplate' = proto.Field( + proto.MESSAGE, + number=8, + message='AwsVolumeTemplate', + ) + main_volume: 'AwsVolumeTemplate' = proto.Field( + proto.MESSAGE, + number=9, + message='AwsVolumeTemplate', + ) + database_encryption: 'AwsDatabaseEncryption' = proto.Field( + proto.MESSAGE, + number=10, + message='AwsDatabaseEncryption', + ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=11, + ) + aws_services_authentication: 'AwsServicesAuthentication' = proto.Field( + proto.MESSAGE, + number=12, + message='AwsServicesAuthentication', + ) + proxy_config: 'AwsProxyConfig' = proto.Field( + proto.MESSAGE, + number=16, + message='AwsProxyConfig', + ) + config_encryption: 'AwsConfigEncryption' = proto.Field( + proto.MESSAGE, + number=17, + message='AwsConfigEncryption', + ) + instance_placement: 'AwsInstancePlacement' = proto.Field( + proto.MESSAGE, + number=18, + message='AwsInstancePlacement', + ) + + +class AwsServicesAuthentication(proto.Message): + r"""Authentication configuration for the management of AWS + resources. + + Attributes: + role_arn (str): + Required. The Amazon Resource Name (ARN) of + the role that the Anthos Multi-Cloud API will + assume when managing AWS resources on your + account. + role_session_name (str): + Optional. An identifier for the assumed role session. + + When unspecified, it defaults to + ``multicloud-service-agent``. + """ + + role_arn: str = proto.Field( + proto.STRING, + number=1, + ) + role_session_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AwsAuthorization(proto.Message): + r"""Configuration related to the cluster RBAC settings. + + Attributes: + admin_users (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsClusterUser]): + Optional. Users that can perform operations as a cluster + admin. A managed ClusterRoleBinding will be created to grant + the ``cluster-admin`` ClusterRole to the users. Up to ten + admin users can be provided. + + For more info on RBAC, see + https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles + admin_groups (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsClusterGroup]): + Optional. Groups of users that can perform operations as a + cluster admin. A managed ClusterRoleBinding will be created + to grant the ``cluster-admin`` ClusterRole to the groups. Up + to ten admin groups can be provided. + + For more info on RBAC, see + https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles + """ + + admin_users: MutableSequence['AwsClusterUser'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AwsClusterUser', + ) + admin_groups: MutableSequence['AwsClusterGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AwsClusterGroup', + ) + + +class AwsClusterUser(proto.Message): + r"""Identities of a user-type subject for AWS clusters. + + Attributes: + username (str): + Required. The name of the user, e.g. + ``my-gcp-id@gmail.com``. + """ + + username: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AwsClusterGroup(proto.Message): + r"""Identities of a group-type subject for AWS clusters. + + Attributes: + group (str): + Required. The name of the group, e.g. + ``my-group@domain.com``. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AwsDatabaseEncryption(proto.Message): + r"""Configuration related to application-layer secrets + encryption. + + Attributes: + kms_key_arn (str): + Required. The ARN of the AWS KMS key used to + encrypt cluster secrets. + """ + + kms_key_arn: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AwsVolumeTemplate(proto.Message): + r"""Configuration template for AWS EBS volumes. + + Attributes: + size_gib (int): + Optional. The size of the volume, in GiBs. + + When unspecified, a default value is provided. + See the specific reference in the parent + resource. + volume_type (google.cloud.gke_multicloud_v1.types.AwsVolumeTemplate.VolumeType): + Optional. Type of the EBS volume. + + When unspecified, it defaults to GP2 volume. + iops (int): + Optional. The number of I/O operations per + second (IOPS) to provision for GP3 volume. + throughput (int): + Optional. The throughput that the volume supports, in MiB/s. + Only valid if volume_type is GP3. + + If the volume_type is GP3 and this is not speficied, it + defaults to 125. + kms_key_arn (str): + Optional. The Amazon Resource Name (ARN) of + the Customer Managed Key (CMK) used to encrypt + AWS EBS volumes. + + If not specified, the default Amazon managed key + associated to the AWS region where this cluster + runs will be used. + """ + class VolumeType(proto.Enum): + r"""Types of supported EBS volumes. We currently only support GP2 + or GP3 volumes. + See + https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html + for more information. + + Values: + VOLUME_TYPE_UNSPECIFIED (0): + Not set. + GP2 (1): + GP2 (General Purpose SSD volume type). + GP3 (2): + GP3 (General Purpose SSD volume type). + """ + VOLUME_TYPE_UNSPECIFIED = 0 + GP2 = 1 + GP3 = 2 + + size_gib: int = proto.Field( + proto.INT32, + number=1, + ) + volume_type: VolumeType = proto.Field( + proto.ENUM, + number=2, + enum=VolumeType, + ) + iops: int = proto.Field( + proto.INT32, + number=3, + ) + throughput: int = proto.Field( + proto.INT32, + number=5, + ) + kms_key_arn: str = proto.Field( + proto.STRING, + number=4, + ) + + +class AwsClusterNetworking(proto.Message): + r"""ClusterNetworking defines cluster-wide networking + configuration. + Anthos clusters on AWS run on a single VPC. This includes + control plane replicas and node pool nodes. + + Attributes: + vpc_id (str): + Required. The VPC associated with the + cluster. All component clusters (i.e. control + plane and node pools) run on a single VPC. + + This field cannot be changed after creation. + pod_address_cidr_blocks (MutableSequence[str]): + Required. All pods in the cluster are + assigned an IPv4 address from these ranges. Only + a single range is supported. This field cannot + be changed after creation. + service_address_cidr_blocks (MutableSequence[str]): + Required. All services in the cluster are + assigned an IPv4 address from these ranges. Only + a single range is supported. This field cannot + be changed after creation. + per_node_pool_sg_rules_disabled (bool): + Optional. Disable the per node pool subnet + security group rules on the control plane + security group. When set to true, you must also + provide one or more security groups that ensure + node pools are able to send requests to the + control plane on TCP/443 and TCP/8132. Failure + to do so may result in unavailable node pools. + """ + + vpc_id: str = proto.Field( + proto.STRING, + number=1, + ) + pod_address_cidr_blocks: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + service_address_cidr_blocks: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + per_node_pool_sg_rules_disabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class AwsNodePool(proto.Message): + r"""An Anthos node pool running on AWS. + + Attributes: + name (str): + The name of this resource. + + Node pool names are formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + For more details on Google Cloud resource names, see + `Resource + Names `__ + version (str): + Required. The Kubernetes version to run on this node pool + (e.g. ``1.19.10-gke.1000``). + + You can list all supported versions on a given Google Cloud + region by calling + [GetAwsServerConfig][google.cloud.gkemulticloud.v1.AwsClusters.GetAwsServerConfig]. + config (google.cloud.gke_multicloud_v1.types.AwsNodeConfig): + Required. The configuration of the node pool. + autoscaling (google.cloud.gke_multicloud_v1.types.AwsNodePoolAutoscaling): + Required. Autoscaler configuration for this + node pool. + subnet_id (str): + Required. The subnet where the node pool node + run. + state (google.cloud.gke_multicloud_v1.types.AwsNodePool.State): + Output only. The lifecycle state of the node + pool. + uid (str): + Output only. A globally unique identifier for + the node pool. + reconciling (bool): + Output only. If set, there are currently + changes in flight to the node pool. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this node pool + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this node pool + was last updated. + etag (str): + Allows clients to perform consistent + read-modify-writes through optimistic + concurrency control. + + Can be sent on update and delete requests to + ensure the client has an up-to-date value before + proceeding. + annotations (MutableMapping[str, str]): + Optional. Annotations on the node pool. + + This field has the same restrictions as Kubernetes + annotations. The total size of all keys and values combined + is limited to 256k. Key can have 2 segments: prefix + (optional) and name (required), separated by a slash (/). + Prefix must be a DNS subdomain. Name must be 63 characters + or less, begin and end with alphanumerics, with dashes (-), + underscores (_), dots (.), and alphanumerics between. + max_pods_constraint (google.cloud.gke_multicloud_v1.types.MaxPodsConstraint): + Required. The constraint on the maximum + number of pods that can be run simultaneously on + a node in the node pool. + errors (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsNodePoolError]): + Output only. A set of errors found in the + node pool. + management (google.cloud.gke_multicloud_v1.types.AwsNodeManagement): + Optional. The Management configuration for + this node pool. + kubelet_config (google.cloud.gke_multicloud_v1.types.NodeKubeletConfig): + Optional. Node kubelet configs. + update_settings (google.cloud.gke_multicloud_v1.types.UpdateSettings): + Optional. Update settings control the speed + and disruption of the update. + """ + class State(proto.Enum): + r"""The lifecycle state of the node pool. + + Values: + STATE_UNSPECIFIED (0): + Not set. + PROVISIONING (1): + The PROVISIONING state indicates the node + pool is being created. + RUNNING (2): + The RUNNING state indicates the node pool has + been created and is fully usable. + RECONCILING (3): + The RECONCILING state indicates that the node + pool is being reconciled. + STOPPING (4): + The STOPPING state indicates the node pool is + being deleted. + ERROR (5): + The ERROR state indicates the node pool is in + a broken unrecoverable state. + DEGRADED (6): + The DEGRADED state indicates the node pool + requires user action to restore full + functionality. + """ + STATE_UNSPECIFIED = 0 + PROVISIONING = 1 + RUNNING = 2 + RECONCILING = 3 + STOPPING = 4 + ERROR = 5 + DEGRADED = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=3, + ) + config: 'AwsNodeConfig' = proto.Field( + proto.MESSAGE, + number=28, + message='AwsNodeConfig', + ) + autoscaling: 'AwsNodePoolAutoscaling' = proto.Field( + proto.MESSAGE, + number=25, + message='AwsNodePoolAutoscaling', + ) + subnet_id: str = proto.Field( + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=16, + enum=State, + ) + uid: str = proto.Field( + proto.STRING, + number=17, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=18, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=20, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=21, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=22, + ) + max_pods_constraint: common_resources.MaxPodsConstraint = proto.Field( + proto.MESSAGE, + number=27, + message=common_resources.MaxPodsConstraint, + ) + errors: MutableSequence['AwsNodePoolError'] = proto.RepeatedField( + proto.MESSAGE, + number=29, + message='AwsNodePoolError', + ) + management: 'AwsNodeManagement' = proto.Field( + proto.MESSAGE, + number=30, + message='AwsNodeManagement', + ) + kubelet_config: common_resources.NodeKubeletConfig = proto.Field( + proto.MESSAGE, + number=31, + message=common_resources.NodeKubeletConfig, + ) + update_settings: 'UpdateSettings' = proto.Field( + proto.MESSAGE, + number=32, + message='UpdateSettings', + ) + + +class UpdateSettings(proto.Message): + r"""UpdateSettings control the level of parallelism and the level of + disruption caused during the update of a node pool. + + These settings are applicable when the node pool update requires + replacing the existing node pool nodes with the updated ones. + + UpdateSettings are optional. When UpdateSettings are not specified + during the node pool creation, a default is chosen based on the + parent cluster's version. For clusters with minor version 1.27 and + later, a default surge_settings configuration with max_surge = 1 and + max_unavailable = 0 is used. For clusters with older versions, node + pool updates use the traditional rolling update mechanism of + updating one node at a time in a "terminate before create" fashion + and update_settings is not applicable. + + Set the surge_settings parameter to use the Surge Update mechanism + for the rolling update of node pool nodes. + + 1. max_surge controls the number of additional nodes that can be + created beyond the current size of the node pool temporarily for + the time of the update to increase the number of available nodes. + 2. max_unavailable controls the number of nodes that can be + simultaneously unavailable during the update. + 3. (max_surge + max_unavailable) determines the level of parallelism + (i.e., the number of nodes being updated at the same time). + + Attributes: + surge_settings (google.cloud.gke_multicloud_v1.types.SurgeSettings): + Optional. Settings for surge update. + """ + + surge_settings: 'SurgeSettings' = proto.Field( + proto.MESSAGE, + number=1, + message='SurgeSettings', + ) + + +class SurgeSettings(proto.Message): + r"""SurgeSettings contains the parameters for Surge update. + + Attributes: + max_surge (int): + Optional. The maximum number of nodes that + can be created beyond the current size of the + node pool during the update process. + max_unavailable (int): + Optional. The maximum number of nodes that + can be simultaneously unavailable during the + update process. A node is considered unavailable + if its status is not Ready. + """ + + max_surge: int = proto.Field( + proto.INT32, + number=1, + ) + max_unavailable: int = proto.Field( + proto.INT32, + number=2, + ) + + +class AwsNodeManagement(proto.Message): + r"""AwsNodeManagement defines the set of node management features + turned on for an AWS node pool. + + Attributes: + auto_repair (bool): + Optional. Whether or not the nodes will be + automatically repaired. When set to true, the + nodes in this node pool will be monitored and if + they fail health checks consistently over a + period of time, an automatic repair action will + be triggered to replace them with new nodes. + """ + + auto_repair: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class AwsNodeConfig(proto.Message): + r"""Parameters that describe the nodes in a cluster. + + Attributes: + instance_type (str): + Optional. The EC2 instance type when creating + on-Demand instances. + If unspecified during node pool creation, a + default will be chosen based on the node pool + version, and assigned to this field. + root_volume (google.cloud.gke_multicloud_v1.types.AwsVolumeTemplate): + Optional. Template for the root volume + provisioned for node pool nodes. Volumes will be + provisioned in the availability zone assigned to + the node pool subnet. + + When unspecified, it defaults to 32 GiB with the + GP2 volume type. + taints (MutableSequence[google.cloud.gke_multicloud_v1.types.NodeTaint]): + Optional. The initial taints assigned to + nodes of this node pool. + labels (MutableMapping[str, str]): + Optional. The initial labels assigned to + nodes of this node pool. An object containing a + list of "key": value pairs. Example: { "name": + "wrench", "mass": "1.3kg", "count": "3" }. + tags (MutableMapping[str, str]): + Optional. Key/value metadata to assign to each underlying + AWS resource. Specify at most 50 pairs containing + alphanumerics, spaces, and symbols (.+-=_:@/). Keys can be + up to 127 Unicode characters. Values can be up to 255 + Unicode characters. + iam_instance_profile (str): + Required. The name or ARN of the AWS IAM + instance profile to assign to nodes in the pool. + image_type (str): + Optional. The OS image type to use on node pool instances. + Can be unspecified, or have a value of ``ubuntu``. + + When unspecified, it defaults to ``ubuntu``. + ssh_config (google.cloud.gke_multicloud_v1.types.AwsSshConfig): + Optional. The SSH configuration. + security_group_ids (MutableSequence[str]): + Optional. The IDs of additional security + groups to add to nodes in this pool. The manager + will automatically create security groups with + minimum rules needed for a functioning cluster. + proxy_config (google.cloud.gke_multicloud_v1.types.AwsProxyConfig): + Optional. Proxy configuration for outbound + HTTP(S) traffic. + config_encryption (google.cloud.gke_multicloud_v1.types.AwsConfigEncryption): + Required. Config encryption for user data. + instance_placement (google.cloud.gke_multicloud_v1.types.AwsInstancePlacement): + Optional. Placement related info for this + node. When unspecified, the VPC's default + tenancy will be used. + autoscaling_metrics_collection (google.cloud.gke_multicloud_v1.types.AwsAutoscalingGroupMetricsCollection): + Optional. Configuration related to CloudWatch + metrics collection on the Auto Scaling group of + the node pool. + + When unspecified, metrics collection is + disabled. + spot_config (google.cloud.gke_multicloud_v1.types.SpotConfig): + Optional. Configuration for provisioning EC2 Spot instances + + When specified, the node pool will provision Spot instances + from the set of spot_config.instance_types. This field is + mutually exclusive with ``instance_type``. + """ + + instance_type: str = proto.Field( + proto.STRING, + number=1, + ) + root_volume: 'AwsVolumeTemplate' = proto.Field( + proto.MESSAGE, + number=2, + message='AwsVolumeTemplate', + ) + taints: MutableSequence[common_resources.NodeTaint] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=common_resources.NodeTaint, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + iam_instance_profile: str = proto.Field( + proto.STRING, + number=6, + ) + image_type: str = proto.Field( + proto.STRING, + number=11, + ) + ssh_config: 'AwsSshConfig' = proto.Field( + proto.MESSAGE, + number=9, + message='AwsSshConfig', + ) + security_group_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + proxy_config: 'AwsProxyConfig' = proto.Field( + proto.MESSAGE, + number=12, + message='AwsProxyConfig', + ) + config_encryption: 'AwsConfigEncryption' = proto.Field( + proto.MESSAGE, + number=13, + message='AwsConfigEncryption', + ) + instance_placement: 'AwsInstancePlacement' = proto.Field( + proto.MESSAGE, + number=14, + message='AwsInstancePlacement', + ) + autoscaling_metrics_collection: 'AwsAutoscalingGroupMetricsCollection' = proto.Field( + proto.MESSAGE, + number=15, + message='AwsAutoscalingGroupMetricsCollection', + ) + spot_config: 'SpotConfig' = proto.Field( + proto.MESSAGE, + number=16, + message='SpotConfig', + ) + + +class AwsNodePoolAutoscaling(proto.Message): + r"""AwsNodePoolAutoscaling contains information required by + cluster autoscaler to adjust the size of the node pool to the + current cluster usage. + + Attributes: + min_node_count (int): + Required. Minimum number of nodes in the node pool. Must be + greater than or equal to 1 and less than or equal to + max_node_count. + max_node_count (int): + Required. Maximum number of nodes in the node pool. Must be + greater than or equal to min_node_count and less than or + equal to 50. + """ + + min_node_count: int = proto.Field( + proto.INT32, + number=1, + ) + max_node_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +class AwsOpenIdConfig(proto.Message): + r"""AwsOpenIdConfig is an OIDC discovery document for the + cluster. See the OpenID Connect Discovery 1.0 specification for + details. + + Attributes: + issuer (str): + OIDC Issuer. + jwks_uri (str): + JSON Web Key uri. + response_types_supported (MutableSequence[str]): + Supported response types. + subject_types_supported (MutableSequence[str]): + Supported subject types. + id_token_signing_alg_values_supported (MutableSequence[str]): + supported ID Token signing Algorithms. + claims_supported (MutableSequence[str]): + Supported claims. + grant_types (MutableSequence[str]): + Supported grant types. + """ + + issuer: str = proto.Field( + proto.STRING, + number=1, + ) + jwks_uri: str = proto.Field( + proto.STRING, + number=2, + ) + response_types_supported: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + subject_types_supported: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + id_token_signing_alg_values_supported: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + claims_supported: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + grant_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class AwsJsonWebKeys(proto.Message): + r"""AwsJsonWebKeys is a valid JSON Web Key Set as specififed in + RFC 7517. + + Attributes: + keys (MutableSequence[google.cloud.gke_multicloud_v1.types.Jwk]): + The public component of the keys used by the + cluster to sign token requests. + """ + + keys: MutableSequence[common_resources.Jwk] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=common_resources.Jwk, + ) + + +class AwsServerConfig(proto.Message): + r"""AwsServerConfig is the configuration of GKE cluster on AWS. + + Attributes: + name (str): + The resource name of the config. + valid_versions (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsK8sVersionInfo]): + List of all released Kubernetes versions, including ones + which are end of life and can no longer be used. Filter by + the ``enabled`` property to limit to currently available + versions. Valid versions supported for both create and + update operations + supported_aws_regions (MutableSequence[str]): + The list of supported AWS regions. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + valid_versions: MutableSequence['AwsK8sVersionInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AwsK8sVersionInfo', + ) + supported_aws_regions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class AwsK8sVersionInfo(proto.Message): + r"""Kubernetes version information of GKE cluster on AWS. + + Attributes: + version (str): + Kubernetes version name. + enabled (bool): + Optional. True if the version is available + for cluster creation. If a version is enabled + for creation, it can be used to create new + clusters. Otherwise, cluster creation will fail. + However, cluster upgrade operations may succeed, + even if the version is not enabled. + end_of_life (bool): + Optional. True if this cluster version + belongs to a minor version that has reached its + end of life and is no longer in scope to receive + security and bug fixes. + end_of_life_date (google.type.date_pb2.Date): + Optional. The estimated date (in Pacific Time) when this + cluster version will reach its end of life. Or if this + version is no longer supported (the ``end_of_life`` field is + true), this is the actual date (in Pacific time) when the + version reached its end of life. + release_date (google.type.date_pb2.Date): + Optional. The date (in Pacific Time) when the + cluster version was released. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + end_of_life: bool = proto.Field( + proto.BOOL, + number=4, + ) + end_of_life_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=5, + message=date_pb2.Date, + ) + release_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=6, + message=date_pb2.Date, + ) + + +class AwsSshConfig(proto.Message): + r"""SSH configuration for AWS resources. + + Attributes: + ec2_key_pair (str): + Required. The name of the EC2 key pair used + to login into cluster machines. + """ + + ec2_key_pair: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AwsProxyConfig(proto.Message): + r"""Details of a proxy config stored in AWS Secret Manager. + + Attributes: + secret_arn (str): + The ARN of the AWS Secret Manager secret that contains the + HTTP(S) proxy configuration. + + The secret must be a JSON encoded proxy configuration as + described in + https://cloud.google.com/kubernetes-engine/multi-cloud/docs/aws/how-to/use-a-proxy#create_a_proxy_configuration_file + secret_version (str): + The version string of the AWS Secret Manager + secret that contains the HTTP(S) proxy + configuration. + """ + + secret_arn: str = proto.Field( + proto.STRING, + number=1, + ) + secret_version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AwsConfigEncryption(proto.Message): + r"""Config encryption for user data. + + Attributes: + kms_key_arn (str): + Required. The ARN of the AWS KMS key used to + encrypt user data. + """ + + kms_key_arn: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AwsInstancePlacement(proto.Message): + r"""Details of placement information for an instance. Limitations for + using the ``host`` tenancy: + + - T3 instances that use the unlimited CPU credit option don't + support host tenancy. + + Attributes: + tenancy (google.cloud.gke_multicloud_v1.types.AwsInstancePlacement.Tenancy): + Required. The tenancy for instance. + """ + class Tenancy(proto.Enum): + r"""Tenancy defines how EC2 instances are distributed across + physical hardware. + + Values: + TENANCY_UNSPECIFIED (0): + Not set. + DEFAULT (1): + Use default VPC tenancy. + DEDICATED (2): + Run a dedicated instance. + HOST (3): + Launch this instance to a dedicated host. + """ + TENANCY_UNSPECIFIED = 0 + DEFAULT = 1 + DEDICATED = 2 + HOST = 3 + + tenancy: Tenancy = proto.Field( + proto.ENUM, + number=1, + enum=Tenancy, + ) + + +class AwsAutoscalingGroupMetricsCollection(proto.Message): + r"""Configuration related to CloudWatch metrics collection in an + AWS Auto Scaling group. + + Attributes: + granularity (str): + Required. The frequency at which EC2 Auto + Scaling sends aggregated data to AWS CloudWatch. + The only valid value is "1Minute". + metrics (MutableSequence[str]): + Optional. The metrics to enable. For a list of valid + metrics, see + https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_EnableMetricsCollection.html. + If you specify Granularity and don't specify any metrics, + all metrics are enabled. + """ + + granularity: str = proto.Field( + proto.STRING, + number=1, + ) + metrics: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class SpotConfig(proto.Message): + r"""SpotConfig has configuration info for Spot node. + + Attributes: + instance_types (MutableSequence[str]): + Required. A list of instance types for + creating spot node pool. + """ + + instance_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class AwsClusterError(proto.Message): + r"""AwsClusterError describes errors found on AWS clusters. + + Attributes: + message (str): + Human-friendly description of the error. + """ + + message: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AwsNodePoolError(proto.Message): + r"""AwsNodePoolError describes errors found on AWS node pools. + + Attributes: + message (str): + Human-friendly description of the error. + """ + + message: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_service.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_service.py new file mode 100644 index 000000000000..61b6badef56f --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_service.py @@ -0,0 +1,850 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.gke_multicloud_v1.types import aws_resources +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkemulticloud.v1', + manifest={ + 'CreateAwsClusterRequest', + 'UpdateAwsClusterRequest', + 'GetAwsClusterRequest', + 'ListAwsClustersRequest', + 'ListAwsClustersResponse', + 'DeleteAwsClusterRequest', + 'CreateAwsNodePoolRequest', + 'UpdateAwsNodePoolRequest', + 'RollbackAwsNodePoolUpdateRequest', + 'GetAwsNodePoolRequest', + 'ListAwsNodePoolsRequest', + 'ListAwsNodePoolsResponse', + 'DeleteAwsNodePoolRequest', + 'GetAwsOpenIdConfigRequest', + 'GetAwsJsonWebKeysRequest', + 'GetAwsServerConfigRequest', + 'GenerateAwsAccessTokenRequest', + 'GenerateAwsAccessTokenResponse', + 'GenerateAwsClusterAgentTokenRequest', + 'GenerateAwsClusterAgentTokenResponse', + }, +) + + +class CreateAwsClusterRequest(proto.Message): + r"""Request message for ``AwsClusters.CreateAwsCluster`` method. + + Attributes: + parent (str): + Required. The parent location where this + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + aws_cluster (google.cloud.gke_multicloud_v1.types.AwsCluster): + Required. The specification of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] to + create. + aws_cluster_id (str): + Required. A client provided ID the resource. Must be unique + within the parent resource. + + The provided ID will be part of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource name formatted as + ``projects//locations//awsClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + validate_only (bool): + If set, only validate the request, but do not + actually create the cluster. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + aws_cluster: aws_resources.AwsCluster = proto.Field( + proto.MESSAGE, + number=2, + message=aws_resources.AwsCluster, + ) + aws_cluster_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateAwsClusterRequest(proto.Message): + r"""Request message for ``AwsClusters.UpdateAwsCluster`` method. + + Attributes: + aws_cluster (google.cloud.gke_multicloud_v1.types.AwsCluster): + Required. The + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource to update. + validate_only (bool): + If set, only validate the request, but do not + actually update the cluster. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. At least one path must + be supplied in this field. The elements of the repeated + paths field can only include these fields from + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]: + + - ``description``. + - ``annotations``. + - ``control_plane.version``. + - ``authorization.admin_users``. + - ``authorization.admin_groups``. + - ``binary_authorization.evaluation_mode``. + - ``control_plane.aws_services_authentication.role_arn``. + - ``control_plane.aws_services_authentication.role_session_name``. + - ``control_plane.config_encryption.kms_key_arn``. + - ``control_plane.instance_type``. + - ``control_plane.security_group_ids``. + - ``control_plane.proxy_config``. + - ``control_plane.proxy_config.secret_arn``. + - ``control_plane.proxy_config.secret_version``. + - ``control_plane.root_volume.size_gib``. + - ``control_plane.root_volume.volume_type``. + - ``control_plane.root_volume.iops``. + - ``control_plane.root_volume.throughput``. + - ``control_plane.root_volume.kms_key_arn``. + - ``control_plane.ssh_config``. + - ``control_plane.ssh_config.ec2_key_pair``. + - ``control_plane.instance_placement.tenancy``. + - ``control_plane.iam_instance_profile``. + - ``logging_config.component_config.enable_components``. + - ``control_plane.tags``. + - ``monitoring_config.managed_prometheus_config.enabled``. + - ``networking.per_node_pool_sg_rules_disabled``. + """ + + aws_cluster: aws_resources.AwsCluster = proto.Field( + proto.MESSAGE, + number=1, + message=aws_resources.AwsCluster, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class GetAwsClusterRequest(proto.Message): + r"""Request message for ``AwsClusters.GetAwsCluster`` method. + + Attributes: + name (str): + Required. The name of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource to describe. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAwsClustersRequest(proto.Message): + r"""Request message for ``AwsClusters.ListAwsClusters`` method. + + Attributes: + parent (str): + Required. The parent location which owns this collection of + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + page_size (int): + The maximum number of items to return. + + If not specified, a default value of 50 will be used by the + service. Regardless of the pageSize value, the response can + include a partial list and a caller should only rely on + response's + [nextPageToken][google.cloud.gkemulticloud.v1.ListAwsClustersResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + The ``nextPageToken`` value returned from a previous + [awsClusters.list][google.cloud.gkemulticloud.v1.AwsClusters.ListAwsClusters] + request, if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAwsClustersResponse(proto.Message): + r"""Response message for ``AwsClusters.ListAwsClusters`` method. + + Attributes: + aws_clusters (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsCluster]): + A list of + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resources in the specified Google Cloud Platform project and + region region. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + aws_clusters: MutableSequence[aws_resources.AwsCluster] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=aws_resources.AwsCluster, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteAwsClusterRequest(proto.Message): + r"""Request message for ``AwsClusters.DeleteAwsCluster`` method. + + Attributes: + name (str): + Required. The resource name the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] to + delete. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + validate_only (bool): + If set, only validate the request, but do not + actually delete the resource. + allow_missing (bool): + If set to true, and the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource is not found, the request will succeed but no + action will be taken on the server and a completed + [Operation][google.longrunning.Operation] will be returned. + + Useful for idempotent deletion. + ignore_errors (bool): + Optional. If set to true, the deletion of + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource will succeed even if errors occur during deleting + in cluster resources. Using this parameter may result in + orphaned resources in the cluster. + etag (str): + The current etag of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + + Allows clients to perform deletions through optimistic + concurrency control. + + If the provided etag does not match the current etag of the + cluster, the request will fail and an ABORTED error will be + returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + ignore_errors: bool = proto.Field( + proto.BOOL, + number=5, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class CreateAwsNodePoolRequest(proto.Message): + r"""Response message for ``AwsClusters.CreateAwsNodePool`` method. + + Attributes: + parent (str): + Required. The + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource where this node pool will be created. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + aws_node_pool (google.cloud.gke_multicloud_v1.types.AwsNodePool): + Required. The specification of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] to + create. + aws_node_pool_id (str): + Required. A client provided ID the resource. Must be unique + within the parent resource. + + The provided ID will be part of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource name formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + validate_only (bool): + If set, only validate the request, but do not + actually create the node pool. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + aws_node_pool: aws_resources.AwsNodePool = proto.Field( + proto.MESSAGE, + number=2, + message=aws_resources.AwsNodePool, + ) + aws_node_pool_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateAwsNodePoolRequest(proto.Message): + r"""Request message for ``AwsClusters.UpdateAwsNodePool`` method. + + Attributes: + aws_node_pool (google.cloud.gke_multicloud_v1.types.AwsNodePool): + Required. The + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource to update. + validate_only (bool): + If set, only validate the request, but don't + actually update the node pool. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. At least one path must + be supplied in this field. The elements of the repeated + paths field can only include these fields from + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]: + + - ``annotations``. + - ``version``. + - ``autoscaling.min_node_count``. + - ``autoscaling.max_node_count``. + - ``config.config_encryption.kms_key_arn``. + - ``config.security_group_ids``. + - ``config.root_volume.iops``. + - ``config.root_volume.throughput``. + - ``config.root_volume.kms_key_arn``. + - ``config.root_volume.volume_type``. + - ``config.root_volume.size_gib``. + - ``config.proxy_config``. + - ``config.proxy_config.secret_arn``. + - ``config.proxy_config.secret_version``. + - ``config.ssh_config``. + - ``config.ssh_config.ec2_key_pair``. + - ``config.instance_placement.tenancy``. + - ``config.iam_instance_profile``. + - ``config.labels``. + - ``config.tags``. + - ``config.autoscaling_metrics_collection``. + - ``config.autoscaling_metrics_collection.granularity``. + - ``config.autoscaling_metrics_collection.metrics``. + - ``config.instance_type``. + - ``management.auto_repair``. + - ``management``. + - ``update_settings``. + - ``update_settings.surge_settings``. + - ``update_settings.surge_settings.max_surge``. + - ``update_settings.surge_settings.max_unavailable``. + """ + + aws_node_pool: aws_resources.AwsNodePool = proto.Field( + proto.MESSAGE, + number=1, + message=aws_resources.AwsNodePool, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class RollbackAwsNodePoolUpdateRequest(proto.Message): + r"""Request message for ``AwsClusters.RollbackAwsNodePoolUpdate`` + method. + + Attributes: + name (str): + Required. The name of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource to rollback. + + ``AwsNodePool`` names are formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + respect_pdb (bool): + Optional. Option for rollback to ignore the + PodDisruptionBudget when draining the node pool + nodes. Default value is false. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + respect_pdb: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class GetAwsNodePoolRequest(proto.Message): + r"""Request message for ``AwsClusters.GetAwsNodePool`` method. + + Attributes: + name (str): + Required. The name of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource to describe. + + ``AwsNodePool`` names are formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAwsNodePoolsRequest(proto.Message): + r"""Request message for ``AwsClusters.ListAwsNodePools`` method. + + Attributes: + parent (str): + Required. The parent ``AwsCluster`` which owns this + collection of + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + page_size (int): + The maximum number of items to return. + + If not specified, a default value of 50 will be used by the + service. Regardless of the pageSize value, the response can + include a partial list and a caller should only rely on + response's + [nextPageToken][google.cloud.gkemulticloud.v1.ListAwsNodePoolsResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + The ``nextPageToken`` value returned from a previous + [awsNodePools.list][google.cloud.gkemulticloud.v1.AwsClusters.ListAwsNodePools] + request, if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAwsNodePoolsResponse(proto.Message): + r"""Response message for ``AwsClusters.ListAwsNodePools`` method. + + Attributes: + aws_node_pools (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsNodePool]): + A list of + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resources in the specified ``AwsCluster``. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + aws_node_pools: MutableSequence[aws_resources.AwsNodePool] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=aws_resources.AwsNodePool, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteAwsNodePoolRequest(proto.Message): + r"""Request message for ``AwsClusters.DeleteAwsNodePool`` method. + + Attributes: + name (str): + Required. The resource name the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] to + delete. + + ``AwsNodePool`` names are formatted as + ``projects//locations//awsClusters//awsNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + validate_only (bool): + If set, only validate the request, but do not + actually delete the node pool. + allow_missing (bool): + If set to true, and the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource is not found, the request will succeed but no + action will be taken on the server and a completed + [Operation][google.longrunning.Operation] will be returned. + + Useful for idempotent deletion. + ignore_errors (bool): + Optional. If set to true, the deletion of + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + resource will succeed even if errors occur during deleting + in node pool resources. Using this parameter may result in + orphaned resources in the node pool. + etag (str): + The current ETag of the + [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. + + Allows clients to perform deletions through optimistic + concurrency control. + + If the provided ETag does not match the current etag of the + node pool, the request will fail and an ABORTED error will + be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + ignore_errors: bool = proto.Field( + proto.BOOL, + number=5, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetAwsOpenIdConfigRequest(proto.Message): + r"""GetAwsOpenIdConfigRequest gets the OIDC discovery document + for the cluster. See the OpenID Connect Discovery 1.0 + specification for details. + + Attributes: + aws_cluster (str): + Required. The AwsCluster, which owns the OIDC + discovery document. Format: + + projects/{project}/locations/{location}/awsClusters/{cluster} + """ + + aws_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetAwsJsonWebKeysRequest(proto.Message): + r"""GetAwsJsonWebKeysRequest gets the public component of the keys used + by the cluster to sign token requests. This will be the jwks_uri for + the discover document returned by getOpenIDConfig. See the OpenID + Connect Discovery 1.0 specification for details. + + Attributes: + aws_cluster (str): + Required. The AwsCluster, which owns the + JsonWebKeys. Format: + + projects/{project}/locations/{location}/awsClusters/{cluster} + """ + + aws_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetAwsServerConfigRequest(proto.Message): + r"""GetAwsServerConfigRequest gets the server config of GKE + cluster on AWS. + + Attributes: + name (str): + Required. The name of the + [AwsServerConfig][google.cloud.gkemulticloud.v1.AwsServerConfig] + resource to describe. + + ``AwsServerConfig`` names are formatted as + ``projects//locations//awsServerConfig``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateAwsAccessTokenRequest(proto.Message): + r"""Request message for ``AwsClusters.GenerateAwsAccessToken`` method. + + Attributes: + aws_cluster (str): + Required. The name of the + [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + resource to authenticate to. + + ``AwsCluster`` names are formatted as + ``projects//locations//awsClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + """ + + aws_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateAwsAccessTokenResponse(proto.Message): + r"""Response message for ``AwsClusters.GenerateAwsAccessToken`` method. + + Attributes: + access_token (str): + Output only. Access token to authenticate to + k8s api-server. + expiration_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp at which the token + will expire. + """ + + access_token: str = proto.Field( + proto.STRING, + number=1, + ) + expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class GenerateAwsClusterAgentTokenRequest(proto.Message): + r""" + + Attributes: + aws_cluster (str): + Required. + subject_token (str): + Required. + subject_token_type (str): + Required. + version (str): + Required. + node_pool_id (str): + Optional. + grant_type (str): + Optional. + audience (str): + Optional. + scope (str): + Optional. + requested_token_type (str): + Optional. + options (str): + Optional. + """ + + aws_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + subject_token: str = proto.Field( + proto.STRING, + number=2, + ) + subject_token_type: str = proto.Field( + proto.STRING, + number=3, + ) + version: str = proto.Field( + proto.STRING, + number=4, + ) + node_pool_id: str = proto.Field( + proto.STRING, + number=5, + ) + grant_type: str = proto.Field( + proto.STRING, + number=6, + ) + audience: str = proto.Field( + proto.STRING, + number=7, + ) + scope: str = proto.Field( + proto.STRING, + number=8, + ) + requested_token_type: str = proto.Field( + proto.STRING, + number=9, + ) + options: str = proto.Field( + proto.STRING, + number=10, + ) + + +class GenerateAwsClusterAgentTokenResponse(proto.Message): + r""" + + Attributes: + access_token (str): + + expires_in (int): + + token_type (str): + + """ + + access_token: str = proto.Field( + proto.STRING, + number=1, + ) + expires_in: int = proto.Field( + proto.INT32, + number=2, + ) + token_type: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_resources.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_resources.py new file mode 100644 index 000000000000..93a31f553c69 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_resources.py @@ -0,0 +1,1398 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.gke_multicloud_v1.types import common_resources +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkemulticloud.v1', + manifest={ + 'AzureCluster', + 'AzureClusterNetworking', + 'AzureControlPlane', + 'ReplicaPlacement', + 'AzureProxyConfig', + 'AzureDatabaseEncryption', + 'AzureConfigEncryption', + 'AzureDiskTemplate', + 'AzureClient', + 'AzureAuthorization', + 'AzureServicesAuthentication', + 'AzureClusterUser', + 'AzureClusterGroup', + 'AzureNodePool', + 'AzureNodeManagement', + 'AzureNodeConfig', + 'AzureNodePoolAutoscaling', + 'AzureOpenIdConfig', + 'AzureJsonWebKeys', + 'AzureServerConfig', + 'AzureK8sVersionInfo', + 'AzureSshConfig', + 'AzureClusterResources', + 'AzureClusterError', + 'AzureNodePoolError', + }, +) + + +class AzureCluster(proto.Message): + r"""An Anthos cluster running on Azure. + + Attributes: + name (str): + The name of this resource. + + Cluster names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + description (str): + Optional. A human readable description of + this cluster. Cannot be longer than 255 UTF-8 + encoded bytes. + azure_region (str): + Required. The Azure region where the cluster runs. + + Each Google Cloud region supports a subset of nearby Azure + regions. You can call + [GetAzureServerConfig][google.cloud.gkemulticloud.v1.AzureClusters.GetAzureServerConfig] + to list all supported Azure regions within a given Google + Cloud region. + resource_group_id (str): + Required. The ARM ID of the resource group where the cluster + resources are deployed. For example: + ``/subscriptions//resourceGroups/`` + azure_client (str): + Optional. Name of the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + that contains authentication configuration for how the + Anthos Multi-Cloud API connects to Azure APIs. + + Either azure_client or azure_services_authentication should + be provided. + + The ``AzureClient`` resource must reside on the same Google + Cloud Platform project and region as the ``AzureCluster``. + + ``AzureClient`` names are formatted as + ``projects//locations//azureClients/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + networking (google.cloud.gke_multicloud_v1.types.AzureClusterNetworking): + Required. Cluster-wide networking + configuration. + control_plane (google.cloud.gke_multicloud_v1.types.AzureControlPlane): + Required. Configuration related to the + cluster control plane. + authorization (google.cloud.gke_multicloud_v1.types.AzureAuthorization): + Required. Configuration related to the + cluster RBAC settings. + azure_services_authentication (google.cloud.gke_multicloud_v1.types.AzureServicesAuthentication): + Optional. Authentication configuration for management of + Azure resources. + + Either azure_client or azure_services_authentication should + be provided. + state (google.cloud.gke_multicloud_v1.types.AzureCluster.State): + Output only. The current state of the + cluster. + endpoint (str): + Output only. The endpoint of the cluster's + API server. + uid (str): + Output only. A globally unique identifier for + the cluster. + reconciling (bool): + Output only. If set, there are currently + changes in flight to the cluster. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this cluster + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this cluster + was last updated. + etag (str): + Allows clients to perform consistent + read-modify-writes through optimistic + concurrency control. + + Can be sent on update and delete requests to + ensure the client has an up-to-date value before + proceeding. + annotations (MutableMapping[str, str]): + Optional. Annotations on the cluster. + + This field has the same restrictions as Kubernetes + annotations. The total size of all keys and values combined + is limited to 256k. Keys can have 2 segments: prefix + (optional) and name (required), separated by a slash (/). + Prefix must be a DNS subdomain. Name must be 63 characters + or less, begin and end with alphanumerics, with dashes (-), + underscores (_), dots (.), and alphanumerics between. + workload_identity_config (google.cloud.gke_multicloud_v1.types.WorkloadIdentityConfig): + Output only. Workload Identity settings. + cluster_ca_certificate (str): + Output only. PEM encoded x509 certificate of + the cluster root of trust. + fleet (google.cloud.gke_multicloud_v1.types.Fleet): + Required. Fleet configuration. + managed_resources (google.cloud.gke_multicloud_v1.types.AzureClusterResources): + Output only. Managed Azure resources for this + cluster. + logging_config (google.cloud.gke_multicloud_v1.types.LoggingConfig): + Optional. Logging configuration for this + cluster. + errors (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureClusterError]): + Output only. A set of errors found in the + cluster. + monitoring_config (google.cloud.gke_multicloud_v1.types.MonitoringConfig): + Optional. Monitoring configuration for this + cluster. + """ + class State(proto.Enum): + r"""The lifecycle state of the cluster. + + Values: + STATE_UNSPECIFIED (0): + Not set. + PROVISIONING (1): + The PROVISIONING state indicates the cluster + is being created. + RUNNING (2): + The RUNNING state indicates the cluster has + been created and is fully usable. + RECONCILING (3): + The RECONCILING state indicates that some + work is actively being done on the cluster, such + as upgrading the control plane replicas. + STOPPING (4): + The STOPPING state indicates the cluster is + being deleted. + ERROR (5): + The ERROR state indicates the cluster is in a + broken unrecoverable state. + DEGRADED (6): + The DEGRADED state indicates the cluster + requires user action to restore full + functionality. + """ + STATE_UNSPECIFIED = 0 + PROVISIONING = 1 + RUNNING = 2 + RECONCILING = 3 + STOPPING = 4 + ERROR = 5 + DEGRADED = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + azure_region: str = proto.Field( + proto.STRING, + number=3, + ) + resource_group_id: str = proto.Field( + proto.STRING, + number=17, + ) + azure_client: str = proto.Field( + proto.STRING, + number=16, + ) + networking: 'AzureClusterNetworking' = proto.Field( + proto.MESSAGE, + number=4, + message='AzureClusterNetworking', + ) + control_plane: 'AzureControlPlane' = proto.Field( + proto.MESSAGE, + number=5, + message='AzureControlPlane', + ) + authorization: 'AzureAuthorization' = proto.Field( + proto.MESSAGE, + number=6, + message='AzureAuthorization', + ) + azure_services_authentication: 'AzureServicesAuthentication' = proto.Field( + proto.MESSAGE, + number=22, + message='AzureServicesAuthentication', + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + endpoint: str = proto.Field( + proto.STRING, + number=8, + ) + uid: str = proto.Field( + proto.STRING, + number=9, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=10, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=13, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + workload_identity_config: common_resources.WorkloadIdentityConfig = proto.Field( + proto.MESSAGE, + number=18, + message=common_resources.WorkloadIdentityConfig, + ) + cluster_ca_certificate: str = proto.Field( + proto.STRING, + number=19, + ) + fleet: common_resources.Fleet = proto.Field( + proto.MESSAGE, + number=20, + message=common_resources.Fleet, + ) + managed_resources: 'AzureClusterResources' = proto.Field( + proto.MESSAGE, + number=21, + message='AzureClusterResources', + ) + logging_config: common_resources.LoggingConfig = proto.Field( + proto.MESSAGE, + number=23, + message=common_resources.LoggingConfig, + ) + errors: MutableSequence['AzureClusterError'] = proto.RepeatedField( + proto.MESSAGE, + number=24, + message='AzureClusterError', + ) + monitoring_config: common_resources.MonitoringConfig = proto.Field( + proto.MESSAGE, + number=25, + message=common_resources.MonitoringConfig, + ) + + +class AzureClusterNetworking(proto.Message): + r"""ClusterNetworking contains cluster-wide networking + configuration. + + Attributes: + virtual_network_id (str): + Required. The Azure Resource Manager (ARM) ID of the VNet + associated with your cluster. + + All components in the cluster (i.e. control plane and node + pools) run on a single VNet. + + Example: + ``/subscriptions//resourceGroups//providers/Microsoft.Network/virtualNetworks/`` + + This field cannot be changed after creation. + pod_address_cidr_blocks (MutableSequence[str]): + Required. The IP address range of the pods in this cluster, + in CIDR notation (e.g. ``10.96.0.0/14``). + + All pods in the cluster get assigned a unique IPv4 address + from these ranges. Only a single range is supported. + + This field cannot be changed after creation. + service_address_cidr_blocks (MutableSequence[str]): + Required. The IP address range for services in this cluster, + in CIDR notation (e.g. ``10.96.0.0/14``). + + All services in the cluster get assigned a unique IPv4 + address from these ranges. Only a single range is supported. + + This field cannot be changed after creating a cluster. + service_load_balancer_subnet_id (str): + Optional. The ARM ID of the subnet where Kubernetes private + service type load balancers are deployed. When unspecified, + it defaults to AzureControlPlane.subnet_id. + + Example: + "/subscriptions/d00494d6-6f3c-4280-bbb2-899e163d1d30/resourceGroups/anthos_cluster_gkeust4/providers/Microsoft.Network/virtualNetworks/gke-vnet-gkeust4/subnets/subnetid456". + """ + + virtual_network_id: str = proto.Field( + proto.STRING, + number=1, + ) + pod_address_cidr_blocks: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + service_address_cidr_blocks: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + service_load_balancer_subnet_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +class AzureControlPlane(proto.Message): + r"""AzureControlPlane represents the control plane + configurations. + + Attributes: + version (str): + Required. The Kubernetes version to run on control plane + replicas (e.g. ``1.19.10-gke.1000``). + + You can list all supported versions on a given Google Cloud + region by calling + [GetAzureServerConfig][google.cloud.gkemulticloud.v1.AzureClusters.GetAzureServerConfig]. + subnet_id (str): + Optional. The ARM ID of the default subnet for the control + plane. The control plane VMs are deployed in this subnet, + unless ``AzureControlPlane.replica_placements`` is + specified. This subnet will also be used as default for + ``AzureControlPlane.endpoint_subnet_id`` if + ``AzureControlPlane.endpoint_subnet_id`` is not specified. + Similarly it will be used as default for + ``AzureClusterNetworking.service_load_balancer_subnet_id``. + + Example: + ``/subscriptions//resourceGroups//providers/Microsoft.Network/virtualNetworks//subnets/default``. + vm_size (str): + Optional. The Azure VM size name. Example: + ``Standard_DS2_v2``. + + For available VM sizes, see + https://docs.microsoft.com/en-us/azure/virtual-machines/vm-naming-conventions. + + When unspecified, it defaults to ``Standard_DS2_v2``. + ssh_config (google.cloud.gke_multicloud_v1.types.AzureSshConfig): + Required. SSH configuration for how to access + the underlying control plane machines. + root_volume (google.cloud.gke_multicloud_v1.types.AzureDiskTemplate): + Optional. Configuration related to the root + volume provisioned for each control plane + replica. + + When unspecified, it defaults to 32-GiB Azure + Disk. + main_volume (google.cloud.gke_multicloud_v1.types.AzureDiskTemplate): + Optional. Configuration related to the main + volume provisioned for each control plane + replica. The main volume is in charge of storing + all of the cluster's etcd state. + + When unspecified, it defaults to a 8-GiB Azure + Disk. + database_encryption (google.cloud.gke_multicloud_v1.types.AzureDatabaseEncryption): + Optional. Configuration related to + application-layer secrets encryption. + proxy_config (google.cloud.gke_multicloud_v1.types.AzureProxyConfig): + Optional. Proxy configuration for outbound + HTTP(S) traffic. + config_encryption (google.cloud.gke_multicloud_v1.types.AzureConfigEncryption): + Optional. Configuration related to vm config + encryption. + tags (MutableMapping[str, str]): + Optional. A set of tags to apply to all + underlying control plane Azure resources. + replica_placements (MutableSequence[google.cloud.gke_multicloud_v1.types.ReplicaPlacement]): + Optional. Configuration for where to place the control plane + replicas. + + Up to three replica placement instances can be specified. If + replica_placements is set, the replica placement instances + will be applied to the three control plane replicas as + evenly as possible. + endpoint_subnet_id (str): + Optional. The ARM ID of the subnet where the control plane + load balancer is deployed. When unspecified, it defaults to + AzureControlPlane.subnet_id. + + Example: + "/subscriptions/d00494d6-6f3c-4280-bbb2-899e163d1d30/resourceGroups/anthos_cluster_gkeust4/providers/Microsoft.Network/virtualNetworks/gke-vnet-gkeust4/subnets/subnetid123". + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + subnet_id: str = proto.Field( + proto.STRING, + number=2, + ) + vm_size: str = proto.Field( + proto.STRING, + number=3, + ) + ssh_config: 'AzureSshConfig' = proto.Field( + proto.MESSAGE, + number=11, + message='AzureSshConfig', + ) + root_volume: 'AzureDiskTemplate' = proto.Field( + proto.MESSAGE, + number=4, + message='AzureDiskTemplate', + ) + main_volume: 'AzureDiskTemplate' = proto.Field( + proto.MESSAGE, + number=5, + message='AzureDiskTemplate', + ) + database_encryption: 'AzureDatabaseEncryption' = proto.Field( + proto.MESSAGE, + number=10, + message='AzureDatabaseEncryption', + ) + proxy_config: 'AzureProxyConfig' = proto.Field( + proto.MESSAGE, + number=12, + message='AzureProxyConfig', + ) + config_encryption: 'AzureConfigEncryption' = proto.Field( + proto.MESSAGE, + number=14, + message='AzureConfigEncryption', + ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + replica_placements: MutableSequence['ReplicaPlacement'] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message='ReplicaPlacement', + ) + endpoint_subnet_id: str = proto.Field( + proto.STRING, + number=15, + ) + + +class ReplicaPlacement(proto.Message): + r"""Configuration for the placement of a control plane replica. + + Attributes: + subnet_id (str): + Required. For a given replica, the ARM ID of + the subnet where the control plane VM is + deployed. Make sure it's a subnet under the + virtual network in the cluster configuration. + azure_availability_zone (str): + Required. For a given replica, the Azure + availability zone where to provision the control + plane VM and the ETCD disk. + """ + + subnet_id: str = proto.Field( + proto.STRING, + number=1, + ) + azure_availability_zone: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AzureProxyConfig(proto.Message): + r"""Details of a proxy config stored in Azure Key Vault. + + Attributes: + resource_group_id (str): + The ARM ID the of the resource group containing proxy + keyvault. + + Resource group ids are formatted as + ``/subscriptions//resourceGroups/``. + secret_id (str): + The URL the of the proxy setting secret with its version. + + The secret must be a JSON encoded proxy configuration as + described in + https://cloud.google.com/kubernetes-engine/multi-cloud/docs/azure/how-to/use-a-proxy#create_a_proxy_configuration_file + + Secret ids are formatted as + ``https://.vault.azure.net/secrets//``. + """ + + resource_group_id: str = proto.Field( + proto.STRING, + number=1, + ) + secret_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AzureDatabaseEncryption(proto.Message): + r"""Configuration related to application-layer secrets + encryption. + Anthos clusters on Azure encrypts your Kubernetes data at rest + in etcd using Azure Key Vault. + + Attributes: + key_id (str): + Required. The ARM ID of the Azure Key Vault key to encrypt / + decrypt data. + + For example: + ``/subscriptions//resourceGroups//providers/Microsoft.KeyVault/vaults//keys/`` + Encryption will always take the latest version of the key + and hence specific version is not supported. + """ + + key_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AzureConfigEncryption(proto.Message): + r"""Configuration related to config data encryption. + + Azure VM bootstrap secret is envelope encrypted with the + provided key vault key. + + Attributes: + key_id (str): + Required. The ARM ID of the Azure Key Vault key to encrypt / + decrypt config data. + + For example: + ``/subscriptions//resourceGroups//providers/Microsoft.KeyVault/vaults//keys/`` + public_key (str): + Optional. RSA key of the Azure Key Vault + public key to use for encrypting the data. + + This key must be formatted as a PEM-encoded + SubjectPublicKeyInfo (RFC 5280) in ASN.1 DER + form. The string must be comprised of a single + PEM block of type "PUBLIC KEY". + """ + + key_id: str = proto.Field( + proto.STRING, + number=2, + ) + public_key: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AzureDiskTemplate(proto.Message): + r"""Configuration for Azure Disks. + + Attributes: + size_gib (int): + Optional. The size of the disk, in GiBs. + + When unspecified, a default value is provided. + See the specific reference in the parent + resource. + """ + + size_gib: int = proto.Field( + proto.INT32, + number=1, + ) + + +class AzureClient(proto.Message): + r"""``AzureClient`` resources hold client authentication information + needed by the Anthos Multi-Cloud API to manage Azure resources on + your Azure subscription. + + When an [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + is created, an ``AzureClient`` resource needs to be provided and all + operations on Azure resources associated to that cluster will + authenticate to Azure services using the given client. + + ``AzureClient`` resources are immutable and cannot be modified upon + creation. + + Each ``AzureClient`` resource is bound to a single Azure Active + Directory Application and tenant. + + Attributes: + name (str): + The name of this resource. + + ``AzureClient`` resource names are formatted as + ``projects//locations//azureClients/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + tenant_id (str): + Required. The Azure Active Directory Tenant + ID. + application_id (str): + Required. The Azure Active Directory + Application ID. + reconciling (bool): + Output only. If set, there are currently + pending changes to the client. + annotations (MutableMapping[str, str]): + Optional. Annotations on the resource. + + This field has the same restrictions as Kubernetes + annotations. The total size of all keys and values combined + is limited to 256k. Keys can have 2 segments: prefix + (optional) and name (required), separated by a slash (/). + Prefix must be a DNS subdomain. Name must be 63 characters + or less, begin and end with alphanumerics, with dashes (-), + underscores (_), dots (.), and alphanumerics between. + pem_certificate (str): + Output only. The PEM encoded x509 + certificate. + uid (str): + Output only. A globally unique identifier for + the client. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this client + was last updated. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + tenant_id: str = proto.Field( + proto.STRING, + number=2, + ) + application_id: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=9, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + pem_certificate: str = proto.Field( + proto.STRING, + number=7, + ) + uid: str = proto.Field( + proto.STRING, + number=5, + ) + 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=10, + message=timestamp_pb2.Timestamp, + ) + + +class AzureAuthorization(proto.Message): + r"""Configuration related to the cluster RBAC settings. + + Attributes: + admin_users (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureClusterUser]): + Optional. Users that can perform operations as a cluster + admin. A managed ClusterRoleBinding will be created to grant + the ``cluster-admin`` ClusterRole to the users. Up to ten + admin users can be provided. + + For more info on RBAC, see + https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles + admin_groups (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureClusterGroup]): + Optional. Groups of users that can perform operations as a + cluster admin. A managed ClusterRoleBinding will be created + to grant the ``cluster-admin`` ClusterRole to the groups. Up + to ten admin groups can be provided. + + For more info on RBAC, see + https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles + """ + + admin_users: MutableSequence['AzureClusterUser'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AzureClusterUser', + ) + admin_groups: MutableSequence['AzureClusterGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AzureClusterGroup', + ) + + +class AzureServicesAuthentication(proto.Message): + r"""Authentication configuration for the management of Azure + resources. + + Attributes: + tenant_id (str): + Required. The Azure Active Directory Tenant + ID. + application_id (str): + Required. The Azure Active Directory + Application ID. + """ + + tenant_id: str = proto.Field( + proto.STRING, + number=1, + ) + application_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AzureClusterUser(proto.Message): + r"""Identities of a user-type subject for Azure clusters. + + Attributes: + username (str): + Required. The name of the user, e.g. + ``my-gcp-id@gmail.com``. + """ + + username: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AzureClusterGroup(proto.Message): + r"""Identities of a group-type subject for Azure clusters. + + Attributes: + group (str): + Required. The name of the group, e.g. + ``my-group@domain.com``. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AzureNodePool(proto.Message): + r"""An Anthos node pool running on Azure. + + Attributes: + name (str): + The name of this resource. + + Node pool names are formatted as + ``projects//locations//azureClusters//azureNodePools/``. + + For more details on Google Cloud resource names, see + `Resource + Names `__ + version (str): + Required. The Kubernetes version (e.g. ``1.19.10-gke.1000``) + running on this node pool. + config (google.cloud.gke_multicloud_v1.types.AzureNodeConfig): + Required. The node configuration of the node + pool. + subnet_id (str): + Required. The ARM ID of the subnet where the + node pool VMs run. Make sure it's a subnet under + the virtual network in the cluster + configuration. + autoscaling (google.cloud.gke_multicloud_v1.types.AzureNodePoolAutoscaling): + Required. Autoscaler configuration for this + node pool. + state (google.cloud.gke_multicloud_v1.types.AzureNodePool.State): + Output only. The current state of the node + pool. + uid (str): + Output only. A globally unique identifier for + the node pool. + reconciling (bool): + Output only. If set, there are currently + pending changes to the node pool. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this node pool + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this node pool + was last updated. + etag (str): + Allows clients to perform consistent + read-modify-writes through optimistic + concurrency control. + + Can be sent on update and delete requests to + ensure the client has an up-to-date value before + proceeding. + annotations (MutableMapping[str, str]): + Optional. Annotations on the node pool. + + This field has the same restrictions as Kubernetes + annotations. The total size of all keys and values combined + is limited to 256k. Keys can have 2 segments: prefix + (optional) and name (required), separated by a slash (/). + Prefix must be a DNS subdomain. Name must be 63 characters + or less, begin and end with alphanumerics, with dashes (-), + underscores (_), dots (.), and alphanumerics between. + max_pods_constraint (google.cloud.gke_multicloud_v1.types.MaxPodsConstraint): + Required. The constraint on the maximum + number of pods that can be run simultaneously on + a node in the node pool. + azure_availability_zone (str): + Optional. The Azure availability zone of the nodes in this + nodepool. + + When unspecified, it defaults to ``1``. + errors (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureNodePoolError]): + Output only. A set of errors found in the + node pool. + management (google.cloud.gke_multicloud_v1.types.AzureNodeManagement): + Optional. The Management configuration for + this node pool. + """ + class State(proto.Enum): + r"""The lifecycle state of the node pool. + + Values: + STATE_UNSPECIFIED (0): + Not set. + PROVISIONING (1): + The PROVISIONING state indicates the node + pool is being created. + RUNNING (2): + The RUNNING state indicates the node pool has + been created and is fully usable. + RECONCILING (3): + The RECONCILING state indicates that the node + pool is being reconciled. + STOPPING (4): + The STOPPING state indicates the node pool is + being deleted. + ERROR (5): + The ERROR state indicates the node pool is in + a broken unrecoverable state. + DEGRADED (6): + The DEGRADED state indicates the node pool + requires user action to restore full + functionality. + """ + STATE_UNSPECIFIED = 0 + PROVISIONING = 1 + RUNNING = 2 + RECONCILING = 3 + STOPPING = 4 + ERROR = 5 + DEGRADED = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + config: 'AzureNodeConfig' = proto.Field( + proto.MESSAGE, + number=22, + message='AzureNodeConfig', + ) + subnet_id: str = proto.Field( + proto.STRING, + number=3, + ) + autoscaling: 'AzureNodePoolAutoscaling' = proto.Field( + proto.MESSAGE, + number=4, + message='AzureNodePoolAutoscaling', + ) + state: State = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + uid: str = proto.Field( + proto.STRING, + number=8, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=9, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=12, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + max_pods_constraint: common_resources.MaxPodsConstraint = proto.Field( + proto.MESSAGE, + number=21, + message=common_resources.MaxPodsConstraint, + ) + azure_availability_zone: str = proto.Field( + proto.STRING, + number=23, + ) + errors: MutableSequence['AzureNodePoolError'] = proto.RepeatedField( + proto.MESSAGE, + number=29, + message='AzureNodePoolError', + ) + management: 'AzureNodeManagement' = proto.Field( + proto.MESSAGE, + number=30, + message='AzureNodeManagement', + ) + + +class AzureNodeManagement(proto.Message): + r"""AzureNodeManagement defines the set of node management + features turned on for an Azure node pool. + + Attributes: + auto_repair (bool): + Optional. Whether or not the nodes will be + automatically repaired. When set to true, the + nodes in this node pool will be monitored and if + they fail health checks consistently over a + period of time, an automatic repair action will + be triggered to replace them with new nodes. + """ + + auto_repair: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class AzureNodeConfig(proto.Message): + r"""Parameters that describe the configuration of all node + machines on a given node pool. + + Attributes: + vm_size (str): + Optional. The Azure VM size name. Example: + ``Standard_DS2_v2``. + + See `Supported VM + sizes `__ + for options. + + When unspecified, it defaults to ``Standard_DS2_v2``. + root_volume (google.cloud.gke_multicloud_v1.types.AzureDiskTemplate): + Optional. Configuration related to the root + volume provisioned for each node pool machine. + + When unspecified, it defaults to a 32-GiB Azure + Disk. + tags (MutableMapping[str, str]): + Optional. A set of tags to apply to all underlying Azure + resources for this node pool. This currently only includes + Virtual Machine Scale Sets. + + Specify at most 50 pairs containing alphanumerics, spaces, + and symbols (.+-=_:@/). Keys can be up to 127 Unicode + characters. Values can be up to 255 Unicode characters. + image_type (str): + Optional. The OS image type to use on node pool instances. + Can be unspecified, or have a value of ``ubuntu``. + + When unspecified, it defaults to ``ubuntu``. + ssh_config (google.cloud.gke_multicloud_v1.types.AzureSshConfig): + Required. SSH configuration for how to access + the node pool machines. + proxy_config (google.cloud.gke_multicloud_v1.types.AzureProxyConfig): + Optional. Proxy configuration for outbound + HTTP(S) traffic. + config_encryption (google.cloud.gke_multicloud_v1.types.AzureConfigEncryption): + Optional. Configuration related to vm config + encryption. + taints (MutableSequence[google.cloud.gke_multicloud_v1.types.NodeTaint]): + Optional. The initial taints assigned to + nodes of this node pool. + labels (MutableMapping[str, str]): + Optional. The initial labels assigned to + nodes of this node pool. An object containing a + list of "key": value pairs. Example: { "name": + "wrench", "mass": "1.3kg", "count": "3" }. + """ + + vm_size: str = proto.Field( + proto.STRING, + number=1, + ) + root_volume: 'AzureDiskTemplate' = proto.Field( + proto.MESSAGE, + number=2, + message='AzureDiskTemplate', + ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + image_type: str = proto.Field( + proto.STRING, + number=8, + ) + ssh_config: 'AzureSshConfig' = proto.Field( + proto.MESSAGE, + number=7, + message='AzureSshConfig', + ) + proxy_config: 'AzureProxyConfig' = proto.Field( + proto.MESSAGE, + number=9, + message='AzureProxyConfig', + ) + config_encryption: 'AzureConfigEncryption' = proto.Field( + proto.MESSAGE, + number=12, + message='AzureConfigEncryption', + ) + taints: MutableSequence[common_resources.NodeTaint] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=common_resources.NodeTaint, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=11, + ) + + +class AzureNodePoolAutoscaling(proto.Message): + r"""Configuration related to Kubernetes cluster autoscaler. + + The Kubernetes cluster autoscaler will automatically adjust the + size of the node pool based on the cluster load. + + Attributes: + min_node_count (int): + Required. Minimum number of nodes in the node pool. Must be + greater than or equal to 1 and less than or equal to + max_node_count. + max_node_count (int): + Required. Maximum number of nodes in the node pool. Must be + greater than or equal to min_node_count and less than or + equal to 50. + """ + + min_node_count: int = proto.Field( + proto.INT32, + number=1, + ) + max_node_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +class AzureOpenIdConfig(proto.Message): + r"""AzureOpenIdConfig is an OIDC discovery document for the + cluster. See the OpenID Connect Discovery 1.0 specification for + details. + + Attributes: + issuer (str): + OIDC Issuer. + jwks_uri (str): + JSON Web Key uri. + response_types_supported (MutableSequence[str]): + Supported response types. + subject_types_supported (MutableSequence[str]): + Supported subject types. + id_token_signing_alg_values_supported (MutableSequence[str]): + supported ID Token signing Algorithms. + claims_supported (MutableSequence[str]): + Supported claims. + grant_types (MutableSequence[str]): + Supported grant types. + """ + + issuer: str = proto.Field( + proto.STRING, + number=1, + ) + jwks_uri: str = proto.Field( + proto.STRING, + number=2, + ) + response_types_supported: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + subject_types_supported: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + id_token_signing_alg_values_supported: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + claims_supported: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + grant_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class AzureJsonWebKeys(proto.Message): + r"""AzureJsonWebKeys is a valid JSON Web Key Set as specififed in + RFC 7517. + + Attributes: + keys (MutableSequence[google.cloud.gke_multicloud_v1.types.Jwk]): + The public component of the keys used by the + cluster to sign token requests. + """ + + keys: MutableSequence[common_resources.Jwk] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=common_resources.Jwk, + ) + + +class AzureServerConfig(proto.Message): + r"""AzureServerConfig contains information about a Google Cloud + location, such as supported Azure regions and Kubernetes + versions. + + Attributes: + name (str): + The ``AzureServerConfig`` resource name. + + ``AzureServerConfig`` names are formatted as + ``projects//locations//azureServerConfig``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + valid_versions (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureK8sVersionInfo]): + List of all released Kubernetes versions, including ones + which are end of life and can no longer be used. Filter by + the ``enabled`` property to limit to currently available + versions. Valid versions supported for both create and + update operations + supported_azure_regions (MutableSequence[str]): + The list of supported Azure regions. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + valid_versions: MutableSequence['AzureK8sVersionInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AzureK8sVersionInfo', + ) + supported_azure_regions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class AzureK8sVersionInfo(proto.Message): + r"""Kubernetes version information of GKE cluster on Azure. + + Attributes: + version (str): + Kubernetes version name (for example, ``1.19.10-gke.1000``) + enabled (bool): + Optional. True if the version is available + for cluster creation. If a version is enabled + for creation, it can be used to create new + clusters. Otherwise, cluster creation will fail. + However, cluster upgrade operations may succeed, + even if the version is not enabled. + end_of_life (bool): + Optional. True if this cluster version + belongs to a minor version that has reached its + end of life and is no longer in scope to receive + security and bug fixes. + end_of_life_date (google.type.date_pb2.Date): + Optional. The estimated date (in Pacific Time) when this + cluster version will reach its end of life. Or if this + version is no longer supported (the ``end_of_life`` field is + true), this is the actual date (in Pacific time) when the + version reached its end of life. + release_date (google.type.date_pb2.Date): + Optional. The date (in Pacific Time) when the + cluster version was released. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + end_of_life: bool = proto.Field( + proto.BOOL, + number=4, + ) + end_of_life_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=5, + message=date_pb2.Date, + ) + release_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=6, + message=date_pb2.Date, + ) + + +class AzureSshConfig(proto.Message): + r"""SSH configuration for Azure resources. + + Attributes: + authorized_key (str): + Required. The SSH public key data for VMs managed by Anthos. + This accepts the authorized_keys file format used in OpenSSH + according to the sshd(8) manual page. + """ + + authorized_key: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AzureClusterResources(proto.Message): + r"""Managed Azure resources for the cluster. + + The values could change and be empty, depending on the state of + the cluster. + + Attributes: + network_security_group_id (str): + Output only. The ARM ID of the cluster + network security group. + control_plane_application_security_group_id (str): + Output only. The ARM ID of the control plane + application security group. + """ + + network_security_group_id: str = proto.Field( + proto.STRING, + number=1, + ) + control_plane_application_security_group_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AzureClusterError(proto.Message): + r"""AzureClusterError describes errors found on Azure clusters. + + Attributes: + message (str): + Human-friendly description of the error. + """ + + message: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AzureNodePoolError(proto.Message): + r"""AzureNodePoolError describes errors found on Azure node + pools. + + Attributes: + message (str): + Human-friendly description of the error. + """ + + message: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_service.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_service.py new file mode 100644 index 000000000000..44c9d74a5e84 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_service.py @@ -0,0 +1,986 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.gke_multicloud_v1.types import azure_resources +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkemulticloud.v1', + manifest={ + 'CreateAzureClusterRequest', + 'UpdateAzureClusterRequest', + 'GetAzureClusterRequest', + 'ListAzureClustersRequest', + 'ListAzureClustersResponse', + 'DeleteAzureClusterRequest', + 'CreateAzureNodePoolRequest', + 'UpdateAzureNodePoolRequest', + 'GetAzureNodePoolRequest', + 'ListAzureNodePoolsRequest', + 'ListAzureNodePoolsResponse', + 'DeleteAzureNodePoolRequest', + 'GetAzureOpenIdConfigRequest', + 'GetAzureJsonWebKeysRequest', + 'GetAzureServerConfigRequest', + 'CreateAzureClientRequest', + 'GetAzureClientRequest', + 'ListAzureClientsRequest', + 'ListAzureClientsResponse', + 'DeleteAzureClientRequest', + 'GenerateAzureAccessTokenRequest', + 'GenerateAzureAccessTokenResponse', + 'GenerateAzureClusterAgentTokenRequest', + 'GenerateAzureClusterAgentTokenResponse', + }, +) + + +class CreateAzureClusterRequest(proto.Message): + r"""Request message for ``AzureClusters.CreateAzureCluster`` method. + + Attributes: + parent (str): + Required. The parent location where this + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + azure_cluster (google.cloud.gke_multicloud_v1.types.AzureCluster): + Required. The specification of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + to create. + azure_cluster_id (str): + Required. A client provided ID the resource. Must be unique + within the parent resource. + + The provided ID will be part of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource name formatted as + ``projects//locations//azureClusters/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + validate_only (bool): + If set, only validate the request, but do not + actually create the cluster. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + azure_cluster: azure_resources.AzureCluster = proto.Field( + proto.MESSAGE, + number=2, + message=azure_resources.AzureCluster, + ) + azure_cluster_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateAzureClusterRequest(proto.Message): + r"""Request message for ``AzureClusters.UpdateAzureCluster`` method. + + Attributes: + azure_cluster (google.cloud.gke_multicloud_v1.types.AzureCluster): + Required. The + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource to update. + validate_only (bool): + If set, only validate the request, but do not + actually update the cluster. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. At least one path must + be supplied in this field. The elements of the repeated + paths field can only include these fields from + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]: + + - ``description``. + - ``azureClient``. + - ``control_plane.version``. + - ``control_plane.vm_size``. + - ``annotations``. + - ``authorization.admin_users``. + - ``authorization.admin_groups``. + - ``control_plane.root_volume.size_gib``. + - ``azure_services_authentication``. + - ``azure_services_authentication.tenant_id``. + - ``azure_services_authentication.application_id``. + - ``control_plane.proxy_config``. + - ``control_plane.proxy_config.resource_group_id``. + - ``control_plane.proxy_config.secret_id``. + - ``control_plane.ssh_config.authorized_key``. + - ``logging_config.component_config.enable_components`` + - ``monitoring_config.managed_prometheus_config.enabled``. + """ + + azure_cluster: azure_resources.AzureCluster = proto.Field( + proto.MESSAGE, + number=1, + message=azure_resources.AzureCluster, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class GetAzureClusterRequest(proto.Message): + r"""Request message for ``AzureClusters.GetAzureCluster`` method. + + Attributes: + name (str): + Required. The name of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource to describe. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAzureClustersRequest(proto.Message): + r"""Request message for ``AzureClusters.ListAzureClusters`` method. + + Attributes: + parent (str): + Required. The parent location which owns this collection of + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + page_size (int): + The maximum number of items to return. + + If not specified, a default value of 50 will be used by the + service. Regardless of the pageSize value, the response can + include a partial list and a caller should only rely on + response's + [nextPageToken][google.cloud.gkemulticloud.v1.ListAzureClustersResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + The ``nextPageToken`` value returned from a previous + [azureClusters.list][google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClusters] + request, if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAzureClustersResponse(proto.Message): + r"""Response message for ``AzureClusters.ListAzureClusters`` method. + + Attributes: + azure_clusters (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureCluster]): + A list of + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resources in the specified Google Cloud Platform project and + region region. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + azure_clusters: MutableSequence[azure_resources.AzureCluster] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=azure_resources.AzureCluster, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteAzureClusterRequest(proto.Message): + r"""Request message for ``AzureClusters.DeleteAzureCluster`` method. + + Attributes: + name (str): + Required. The resource name the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + to delete. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + allow_missing (bool): + If set to true, and the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource is not found, the request will succeed but no + action will be taken on the server and a completed + [Operation][google.longrunning.Operation] will be returned. + + Useful for idempotent deletion. + validate_only (bool): + If set, only validate the request, but do not + actually delete the resource. + etag (str): + The current etag of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + + Allows clients to perform deletions through optimistic + concurrency control. + + If the provided etag does not match the current etag of the + cluster, the request will fail and an ABORTED error will be + returned. + ignore_errors (bool): + Optional. If set to true, the deletion of + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource will succeed even if errors occur during deleting + in cluster resources. Using this parameter may result in + orphaned resources in the cluster. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + ignore_errors: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CreateAzureNodePoolRequest(proto.Message): + r"""Response message for ``AzureClusters.CreateAzureNodePool`` method. + + Attributes: + parent (str): + Required. The + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource where this node pool will be created. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + azure_node_pool (google.cloud.gke_multicloud_v1.types.AzureNodePool): + Required. The specification of the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + to create. + azure_node_pool_id (str): + Required. A client provided ID the resource. Must be unique + within the parent resource. + + The provided ID will be part of the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource name formatted as + ``projects//locations//azureClusters//azureNodePools/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + validate_only (bool): + If set, only validate the request, but do not + actually create the node pool. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + azure_node_pool: azure_resources.AzureNodePool = proto.Field( + proto.MESSAGE, + number=2, + message=azure_resources.AzureNodePool, + ) + azure_node_pool_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateAzureNodePoolRequest(proto.Message): + r"""Request message for ``AzureClusters.UpdateAzureNodePool`` method. + + Attributes: + azure_node_pool (google.cloud.gke_multicloud_v1.types.AzureNodePool): + Required. The + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource to update. + validate_only (bool): + If set, only validate the request, but don't + actually update the node pool. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. At least one path must + be supplied in this field. The elements of the repeated + paths field can only include these fields from + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]: + + \*. ``annotations``. + + - ``version``. + - ``autoscaling.min_node_count``. + - ``autoscaling.max_node_count``. + - ``config.ssh_config.authorized_key``. + - ``management.auto_repair``. + - ``management``. + """ + + azure_node_pool: azure_resources.AzureNodePool = proto.Field( + proto.MESSAGE, + number=1, + message=azure_resources.AzureNodePool, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class GetAzureNodePoolRequest(proto.Message): + r"""Request message for ``AzureClusters.GetAzureNodePool`` method. + + Attributes: + name (str): + Required. The name of the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource to describe. + + ``AzureNodePool`` names are formatted as + ``projects//locations//azureClusters//azureNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAzureNodePoolsRequest(proto.Message): + r"""Request message for ``AzureClusters.ListAzureNodePools`` method. + + Attributes: + parent (str): + Required. The parent ``AzureCluster`` which owns this + collection of + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + page_size (int): + The maximum number of items to return. + + If not specified, a default value of 50 will be used by the + service. Regardless of the pageSize value, the response can + include a partial list and a caller should only rely on + response's + [nextPageToken][google.cloud.gkemulticloud.v1.ListAzureNodePoolsResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + The ``nextPageToken`` value returned from a previous + [azureNodePools.list][google.cloud.gkemulticloud.v1.AzureClusters.ListAzureNodePools] + request, if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAzureNodePoolsResponse(proto.Message): + r"""Response message for ``AzureClusters.ListAzureNodePools`` method. + + Attributes: + azure_node_pools (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureNodePool]): + A list of + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resources in the specified ``AzureCluster``. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + azure_node_pools: MutableSequence[azure_resources.AzureNodePool] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=azure_resources.AzureNodePool, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteAzureNodePoolRequest(proto.Message): + r"""Request message for ``AzureClusters.DeleteAzureNodePool`` method. + + Attributes: + name (str): + Required. The resource name the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + to delete. + + ``AzureNodePool`` names are formatted as + ``projects//locations//azureClusters//azureNodePools/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + validate_only (bool): + If set, only validate the request, but do not + actually delete the node pool. + allow_missing (bool): + If set to true, and the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource is not found, the request will succeed but no + action will be taken on the server and a completed + [Operation][google.longrunning.Operation] will be returned. + + Useful for idempotent deletion. + etag (str): + The current ETag of the + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. + + Allows clients to perform deletions through optimistic + concurrency control. + + If the provided ETag does not match the current etag of the + node pool, the request will fail and an ABORTED error will + be returned. + ignore_errors (bool): + Optional. If set to true, the deletion of + [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + resource will succeed even if errors occur during deleting + in node pool resources. Using this parameter may result in + orphaned resources in the node pool. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + ignore_errors: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class GetAzureOpenIdConfigRequest(proto.Message): + r"""GetAzureOpenIdConfigRequest gets the OIDC discovery document + for the cluster. See the OpenID Connect Discovery 1.0 + specification for details. + + Attributes: + azure_cluster (str): + Required. The AzureCluster, which owns the + OIDC discovery document. Format: + + projects//locations//azureClusters/ + """ + + azure_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetAzureJsonWebKeysRequest(proto.Message): + r"""GetAzureJsonWebKeysRequest gets the public component of the keys + used by the cluster to sign token requests. This will be the + jwks_uri for the discover document returned by getOpenIDConfig. See + the OpenID Connect Discovery 1.0 specification for details. + + Attributes: + azure_cluster (str): + Required. The AzureCluster, which owns the JsonWebKeys. + Format: + ``projects//locations//azureClusters/`` + """ + + azure_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetAzureServerConfigRequest(proto.Message): + r"""GetAzureServerConfigRequest gets the server config of GKE + cluster on Azure. + + Attributes: + name (str): + Required. The name of the + [AzureServerConfig][google.cloud.gkemulticloud.v1.AzureServerConfig] + resource to describe. + + ``AzureServerConfig`` names are formatted as + ``projects//locations//azureServerConfig``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAzureClientRequest(proto.Message): + r"""Request message for ``AzureClusters.CreateAzureClient`` method. + + Attributes: + parent (str): + Required. The parent location where this + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource will be created. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + azure_client (google.cloud.gke_multicloud_v1.types.AzureClient): + Required. The specification of the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] to + create. + azure_client_id (str): + Required. A client provided ID the resource. Must be unique + within the parent resource. + + The provided ID will be part of the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource name formatted as + ``projects//locations//azureClients/``. + + Valid characters are ``/[a-z][0-9]-/``. Cannot be longer + than 63 characters. + validate_only (bool): + If set, only validate the request, but do not + actually create the client. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + azure_client: azure_resources.AzureClient = proto.Field( + proto.MESSAGE, + number=2, + message=azure_resources.AzureClient, + ) + azure_client_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GetAzureClientRequest(proto.Message): + r"""Request message for ``AzureClusters.GetAzureClient`` method. + + Attributes: + name (str): + Required. The name of the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource to describe. + + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + names are formatted as + ``projects//locations//azureClients/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAzureClientsRequest(proto.Message): + r"""Request message for ``AzureClusters.ListAzureClients`` method. + + Attributes: + parent (str): + Required. The parent location which owns this collection of + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resources. + + Location names are formatted as + ``projects//locations/``. + + See `Resource + Names `__ + for more details on Google Cloud Platform resource names. + page_size (int): + The maximum number of items to return. + + If not specified, a default value of 50 will be used by the + service. Regardless of the pageSize value, the response can + include a partial list and a caller should only rely on + response's + [nextPageToken][google.cloud.gkemulticloud.v1.ListAzureClientsResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + The ``nextPageToken`` value returned from a previous + [azureClients.list][google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClients] + request, if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAzureClientsResponse(proto.Message): + r"""Response message for ``AzureClusters.ListAzureClients`` method. + + Attributes: + azure_clients (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureClient]): + A list of + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resources in the specified Google Cloud project and region + region. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + azure_clients: MutableSequence[azure_resources.AzureClient] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=azure_resources.AzureClient, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteAzureClientRequest(proto.Message): + r"""Request message for ``AzureClusters.DeleteAzureClient`` method. + + Attributes: + name (str): + Required. The resource name the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] to + delete. + + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + names are formatted as + ``projects//locations//azureClients/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + allow_missing (bool): + If set to true, and the + [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + resource is not found, the request will succeed but no + action will be taken on the server and a completed + [Operation][google.longrunning.Operation] will be returned. + + Useful for idempotent deletion. + validate_only (bool): + If set, only validate the request, but do not + actually delete the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GenerateAzureAccessTokenRequest(proto.Message): + r"""Request message for ``AzureClusters.GenerateAzureAccessToken`` + method. + + Attributes: + azure_cluster (str): + Required. The name of the + [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + resource to authenticate to. + + ``AzureCluster`` names are formatted as + ``projects//locations//azureClusters/``. + + See `Resource + Names `__ + for more details on Google Cloud resource names. + """ + + azure_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateAzureAccessTokenResponse(proto.Message): + r"""Response message for ``AzureClusters.GenerateAzureAccessToken`` + method. + + Attributes: + access_token (str): + Output only. Access token to authenticate to + k8s api-server. + expiration_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp at which the token + will expire. + """ + + access_token: str = proto.Field( + proto.STRING, + number=1, + ) + expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class GenerateAzureClusterAgentTokenRequest(proto.Message): + r""" + + Attributes: + azure_cluster (str): + Required. + subject_token (str): + Required. + subject_token_type (str): + Required. + version (str): + Required. + node_pool_id (str): + Optional. + grant_type (str): + Optional. + audience (str): + Optional. + scope (str): + Optional. + requested_token_type (str): + Optional. + options (str): + Optional. + """ + + azure_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + subject_token: str = proto.Field( + proto.STRING, + number=2, + ) + subject_token_type: str = proto.Field( + proto.STRING, + number=3, + ) + version: str = proto.Field( + proto.STRING, + number=4, + ) + node_pool_id: str = proto.Field( + proto.STRING, + number=5, + ) + grant_type: str = proto.Field( + proto.STRING, + number=6, + ) + audience: str = proto.Field( + proto.STRING, + number=7, + ) + scope: str = proto.Field( + proto.STRING, + number=8, + ) + requested_token_type: str = proto.Field( + proto.STRING, + number=9, + ) + options: str = proto.Field( + proto.STRING, + number=10, + ) + + +class GenerateAzureClusterAgentTokenResponse(proto.Message): + r""" + + Attributes: + access_token (str): + + expires_in (int): + + token_type (str): + + """ + + access_token: str = proto.Field( + proto.STRING, + number=1, + ) + expires_in: int = proto.Field( + proto.INT32, + number=2, + ) + token_type: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/common_resources.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/common_resources.py new file mode 100644 index 000000000000..23539815d1f1 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/common_resources.py @@ -0,0 +1,576 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkemulticloud.v1', + manifest={ + 'Jwk', + 'WorkloadIdentityConfig', + 'MaxPodsConstraint', + 'OperationMetadata', + 'NodeTaint', + 'NodeKubeletConfig', + 'Fleet', + 'LoggingConfig', + 'LoggingComponentConfig', + 'MonitoringConfig', + 'ManagedPrometheusConfig', + 'CloudMonitoringConfig', + 'BinaryAuthorization', + 'SecurityPostureConfig', + }, +) + + +class Jwk(proto.Message): + r"""Jwk is a JSON Web Key as specified in RFC 7517. + + Attributes: + kty (str): + Key Type. + alg (str): + Algorithm. + use (str): + Permitted uses for the public keys. + kid (str): + Key ID. + n (str): + Used for RSA keys. + e (str): + Used for RSA keys. + x (str): + Used for ECDSA keys. + y (str): + Used for ECDSA keys. + crv (str): + Used for ECDSA keys. + """ + + kty: str = proto.Field( + proto.STRING, + number=1, + ) + alg: str = proto.Field( + proto.STRING, + number=2, + ) + use: str = proto.Field( + proto.STRING, + number=3, + ) + kid: str = proto.Field( + proto.STRING, + number=4, + ) + n: str = proto.Field( + proto.STRING, + number=5, + ) + e: str = proto.Field( + proto.STRING, + number=6, + ) + x: str = proto.Field( + proto.STRING, + number=7, + ) + y: str = proto.Field( + proto.STRING, + number=8, + ) + crv: str = proto.Field( + proto.STRING, + number=9, + ) + + +class WorkloadIdentityConfig(proto.Message): + r"""Workload Identity settings. + + Attributes: + issuer_uri (str): + The OIDC issuer URL for this cluster. + workload_pool (str): + The Workload Identity Pool associated to the + cluster. + identity_provider (str): + The ID of the OIDC Identity Provider (IdP) + associated to the Workload Identity Pool. + """ + + issuer_uri: str = proto.Field( + proto.STRING, + number=1, + ) + workload_pool: str = proto.Field( + proto.STRING, + number=2, + ) + identity_provider: str = proto.Field( + proto.STRING, + number=3, + ) + + +class MaxPodsConstraint(proto.Message): + r"""Constraints applied to pods. + + Attributes: + max_pods_per_node (int): + Required. The maximum number of pods to + schedule on a single node. + """ + + max_pods_per_node: int = proto.Field( + proto.INT64, + number=1, + ) + + +class OperationMetadata(proto.Message): + r"""Metadata about a long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this operation + was created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this operation + was completed. + target (str): + Output only. The name of the resource + associated to this operation. + status_detail (str): + Output only. Human-readable status of the + operation, if any. + error_detail (str): + Output only. Human-readable status of any + error that occurred during the operation. + verb (str): + Output only. The verb associated with the API + method which triggered this operation. Possible + values are "create", "delete", "update" and + "import". + requested_cancellation (bool): + Output only. Identifies whether it has been requested + cancellation for the operation. Operations that have + successfully been cancelled have + [google.longrunning.Operation.error][google.longrunning.Operation.error] + value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. + """ + + 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, + ) + status_detail: str = proto.Field( + proto.STRING, + number=4, + ) + error_detail: str = proto.Field( + proto.STRING, + number=5, + ) + verb: str = proto.Field( + proto.STRING, + number=7, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class NodeTaint(proto.Message): + r"""The taint content for the node taint. + + Attributes: + key (str): + Required. Key for the taint. + value (str): + Required. Value for the taint. + effect (google.cloud.gke_multicloud_v1.types.NodeTaint.Effect): + Required. The taint effect. + """ + class Effect(proto.Enum): + r"""The taint effect. + + Values: + EFFECT_UNSPECIFIED (0): + Not set. + NO_SCHEDULE (1): + Do not allow new pods to schedule onto the + node unless they tolerate the taint, but allow + all pods submitted to Kubelet without going + through the scheduler to start, and allow all + already-running pods to continue running. + Enforced by the scheduler. + PREFER_NO_SCHEDULE (2): + Like TaintEffectNoSchedule, but the scheduler + tries not to schedule new pods onto the node, + rather than prohibiting new pods from scheduling + onto the node entirely. Enforced by the + scheduler. + NO_EXECUTE (3): + Evict any already-running pods that do not + tolerate the taint. Currently enforced by + NodeController. + """ + EFFECT_UNSPECIFIED = 0 + NO_SCHEDULE = 1 + PREFER_NO_SCHEDULE = 2 + NO_EXECUTE = 3 + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + effect: Effect = proto.Field( + proto.ENUM, + number=3, + enum=Effect, + ) + + +class NodeKubeletConfig(proto.Message): + r"""Configuration for node pool kubelet options. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + insecure_kubelet_readonly_port_enabled (bool): + Optional. Enable the insecure kubelet read + only port. + cpu_manager_policy (str): + Optional. Control the CPU management policy on the node. See + https://kubernetes.io/docs/tasks/administer-cluster/cpu-management-policies/ + + The following values are allowed. + + - "none": the default, which represents the existing + scheduling behavior. + - "static": allows pods with certain resource + characteristics to be granted increased CPU affinity and + exclusivity on the node. The default value is 'none' if + unspecified. + + This field is a member of `oneof`_ ``_cpu_manager_policy``. + cpu_cfs_quota (bool): + Optional. Enable CPU CFS quota enforcement + for containers that specify CPU limits. + + This option is enabled by default which makes + kubelet use CFS quota + (https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt) + to enforce container CPU limits. Otherwise, CPU + limits will not be enforced at all. + + Disable this option to mitigate CPU throttling + problems while still having your pods to be in + Guaranteed QoS class by specifying the CPU + limits. + + The default value is 'true' if unspecified. + + This field is a member of `oneof`_ ``_cpu_cfs_quota``. + cpu_cfs_quota_period (str): + Optional. Set the CPU CFS quota period value + 'cpu.cfs_period_us'. + + The string must be a sequence of decimal numbers, each with + optional fraction and a unit suffix, such as "300ms". Valid + time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + The value must be a positive duration. + + The default value is '100ms' if unspecified. + + This field is a member of `oneof`_ ``_cpu_cfs_quota_period``. + pod_pids_limit (int): + Optional. Set the Pod PID limits. See + https://kubernetes.io/docs/concepts/policy/pid-limiting/#pod-pid-limits + + Controls the maximum number of processes allowed + to run in a pod. The value must be greater than + or equal to 1024 and less than 4194304. + + This field is a member of `oneof`_ ``_pod_pids_limit``. + """ + + insecure_kubelet_readonly_port_enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + cpu_manager_policy: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + cpu_cfs_quota: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + cpu_cfs_quota_period: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + pod_pids_limit: int = proto.Field( + proto.INT64, + number=5, + optional=True, + ) + + +class Fleet(proto.Message): + r"""Fleet related configuration. + + Fleets are a Google Cloud concept for logically organizing clusters, + letting you use and manage multi-cluster capabilities and apply + consistent policies across your systems. + + See `Anthos + Fleets `__ + for more details on Anthos multi-cluster capabilities using Fleets. + + Attributes: + project (str): + Required. The name of the Fleet host project where this + cluster will be registered. + + Project names are formatted as + ``projects/``. + membership (str): + Output only. The name of the managed Hub Membership resource + associated to this cluster. + + Membership names are formatted as + ``projects//locations/global/membership/``. + """ + + project: str = proto.Field( + proto.STRING, + number=1, + ) + membership: str = proto.Field( + proto.STRING, + number=2, + ) + + +class LoggingConfig(proto.Message): + r"""Parameters that describe the Logging configuration in a + cluster. + + Attributes: + component_config (google.cloud.gke_multicloud_v1.types.LoggingComponentConfig): + The configuration of the logging components; + """ + + component_config: 'LoggingComponentConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='LoggingComponentConfig', + ) + + +class LoggingComponentConfig(proto.Message): + r"""Parameters that describe the Logging component configuration + in a cluster. + + Attributes: + enable_components (MutableSequence[google.cloud.gke_multicloud_v1.types.LoggingComponentConfig.Component]): + The components to be enabled. + """ + class Component(proto.Enum): + r"""The components of the logging configuration; + + Values: + COMPONENT_UNSPECIFIED (0): + No component is specified + SYSTEM_COMPONENTS (1): + This indicates that system logging components + is enabled. + WORKLOADS (2): + This indicates that user workload logging + component is enabled. + """ + COMPONENT_UNSPECIFIED = 0 + SYSTEM_COMPONENTS = 1 + WORKLOADS = 2 + + enable_components: MutableSequence[Component] = proto.RepeatedField( + proto.ENUM, + number=1, + enum=Component, + ) + + +class MonitoringConfig(proto.Message): + r"""Parameters that describe the Monitoring configuration in a + cluster. + + Attributes: + managed_prometheus_config (google.cloud.gke_multicloud_v1.types.ManagedPrometheusConfig): + Enable Google Cloud Managed Service for + Prometheus in the cluster. + cloud_monitoring_config (google.cloud.gke_multicloud_v1.types.CloudMonitoringConfig): + Optionally enable GKE metrics. + Only for Attached Clusters. + """ + + managed_prometheus_config: 'ManagedPrometheusConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='ManagedPrometheusConfig', + ) + cloud_monitoring_config: 'CloudMonitoringConfig' = proto.Field( + proto.MESSAGE, + number=4, + message='CloudMonitoringConfig', + ) + + +class ManagedPrometheusConfig(proto.Message): + r"""ManagedPrometheusConfig defines the configuration for + Google Cloud Managed Service for Prometheus. + + Attributes: + enabled (bool): + Enable Managed Collection. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class CloudMonitoringConfig(proto.Message): + r"""CloudMonitoringConfig defines the configuration for + built-in Cloud Logging and Monitoring. + Only for Attached Clusters. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enabled (bool): + Enable GKE-native logging and metrics. + Only for Attached Clusters. + + This field is a member of `oneof`_ ``_enabled``. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + + +class BinaryAuthorization(proto.Message): + r"""Configuration for Binary Authorization. + + Attributes: + evaluation_mode (google.cloud.gke_multicloud_v1.types.BinaryAuthorization.EvaluationMode): + Mode of operation for binauthz policy + evaluation. If unspecified, defaults to + DISABLED. + """ + class EvaluationMode(proto.Enum): + r"""Binary Authorization mode of operation. + + Values: + EVALUATION_MODE_UNSPECIFIED (0): + Default value + DISABLED (1): + Disable BinaryAuthorization + PROJECT_SINGLETON_POLICY_ENFORCE (2): + Enforce Kubernetes admission requests with + BinaryAuthorization using the project's + singleton policy. + """ + EVALUATION_MODE_UNSPECIFIED = 0 + DISABLED = 1 + PROJECT_SINGLETON_POLICY_ENFORCE = 2 + + evaluation_mode: EvaluationMode = proto.Field( + proto.ENUM, + number=1, + enum=EvaluationMode, + ) + + +class SecurityPostureConfig(proto.Message): + r"""SecurityPostureConfig defines the flags needed to + enable/disable features for the Security Posture API. + + Attributes: + vulnerability_mode (google.cloud.gke_multicloud_v1.types.SecurityPostureConfig.VulnerabilityMode): + Sets which mode to use for vulnerability + scanning. + """ + class VulnerabilityMode(proto.Enum): + r"""VulnerabilityMode defines enablement mode for vulnerability + scanning. + + Values: + VULNERABILITY_MODE_UNSPECIFIED (0): + Default value not specified. + VULNERABILITY_DISABLED (1): + Disables vulnerability scanning on the + cluster. + VULNERABILITY_ENTERPRISE (2): + Applies the Security Posture's vulnerability + on cluster Enterprise level features. + """ + VULNERABILITY_MODE_UNSPECIFIED = 0 + VULNERABILITY_DISABLED = 1 + VULNERABILITY_ENTERPRISE = 2 + + vulnerability_mode: VulnerabilityMode = proto.Field( + proto.ENUM, + number=1, + enum=VulnerabilityMode, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/mypy.ini b/owl-bot-staging/google-cloud-gke-multicloud/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/noxfile.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/noxfile.py new file mode 100644 index 000000000000..5736281f802e --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import re +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-gke-multicloud' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/gke_multicloud_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/gke_multicloud_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '-p', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py new file mode 100644 index 000000000000..3e9e298ad4a1 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAttachedCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_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 gke_multicloud_v1 + + +async def sample_create_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + attached_cluster = gke_multicloud_v1.AttachedCluster() + attached_cluster.platform_version = "platform_version_value" + attached_cluster.distribution = "distribution_value" + attached_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAttachedClusterRequest( + parent="parent_value", + attached_cluster=attached_cluster, + attached_cluster_id="attached_cluster_id_value", + ) + + # Make the request + operation = client.create_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py new file mode 100644 index 000000000000..fcd93bbd900c --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAttachedCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_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 gke_multicloud_v1 + + +def sample_create_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + attached_cluster = gke_multicloud_v1.AttachedCluster() + attached_cluster.platform_version = "platform_version_value" + attached_cluster.distribution = "distribution_value" + attached_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAttachedClusterRequest( + parent="parent_value", + attached_cluster=attached_cluster, + attached_cluster_id="attached_cluster_id_value", + ) + + # Make the request + operation = client.create_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py new file mode 100644 index 000000000000..26add76e189c --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAttachedCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_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 gke_multicloud_v1 + + +async def sample_delete_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAttachedClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py new file mode 100644 index 000000000000..ed906b0ac7fe --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAttachedCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_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 gke_multicloud_v1 + + +def sample_delete_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAttachedClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py new file mode 100644 index 000000000000..14e7c5e9afb4 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAttachedClusterAgentToken +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_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 gke_multicloud_v1 + + +async def sample_generate_attached_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAttachedClusterAgentTokenRequest( + attached_cluster="attached_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = await client.generate_attached_cluster_agent_token(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py new file mode 100644 index 000000000000..40d3bf89d09d --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAttachedClusterAgentToken +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_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 gke_multicloud_v1 + + +def sample_generate_attached_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAttachedClusterAgentTokenRequest( + attached_cluster="attached_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = client.generate_attached_cluster_agent_token(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py new file mode 100644 index 000000000000..544e71cdbc9c --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAttachedClusterInstallManifest +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_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 gke_multicloud_v1 + + +async def sample_generate_attached_cluster_install_manifest(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAttachedClusterInstallManifestRequest( + parent="parent_value", + attached_cluster_id="attached_cluster_id_value", + platform_version="platform_version_value", + ) + + # Make the request + response = await client.generate_attached_cluster_install_manifest(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py new file mode 100644 index 000000000000..ed3a9fe0075e --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAttachedClusterInstallManifest +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_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 gke_multicloud_v1 + + +def sample_generate_attached_cluster_install_manifest(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAttachedClusterInstallManifestRequest( + parent="parent_value", + attached_cluster_id="attached_cluster_id_value", + platform_version="platform_version_value", + ) + + # Make the request + response = client.generate_attached_cluster_install_manifest(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py new file mode 100644 index 000000000000..b5d7da17a336 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttachedCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_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 gke_multicloud_v1 + + +async def sample_get_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAttachedClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attached_cluster(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py new file mode 100644 index 000000000000..1b21ca1906a3 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttachedCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_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 gke_multicloud_v1 + + +def sample_get_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAttachedClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_attached_cluster(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py new file mode 100644 index 000000000000..827c4d5c6540 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttachedServerConfig +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_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 gke_multicloud_v1 + + +async def sample_get_attached_server_config(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAttachedServerConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attached_server_config(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py new file mode 100644 index 000000000000..76490ea3abd0 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttachedServerConfig +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_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 gke_multicloud_v1 + + +def sample_get_attached_server_config(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAttachedServerConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_attached_server_config(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py new file mode 100644 index 000000000000..9b94d8986875 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportAttachedCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_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 gke_multicloud_v1 + + +async def sample_import_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ImportAttachedClusterRequest( + parent="parent_value", + fleet_membership="fleet_membership_value", + platform_version="platform_version_value", + distribution="distribution_value", + ) + + # Make the request + operation = client.import_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py new file mode 100644 index 000000000000..59c919ab77a2 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportAttachedCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_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 gke_multicloud_v1 + + +def sample_import_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ImportAttachedClusterRequest( + parent="parent_value", + fleet_membership="fleet_membership_value", + platform_version="platform_version_value", + distribution="distribution_value", + ) + + # Make the request + operation = client.import_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py new file mode 100644 index 000000000000..bc0bb3e08bf1 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAttachedClusters +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_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 gke_multicloud_v1 + + +async def sample_list_attached_clusters(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAttachedClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attached_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py new file mode 100644 index 000000000000..c30c113a6b3f --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAttachedClusters +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_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 gke_multicloud_v1 + + +def sample_list_attached_clusters(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAttachedClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attached_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py new file mode 100644 index 000000000000..ebbf06cbdb91 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttachedCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_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 gke_multicloud_v1 + + +async def sample_update_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersAsyncClient() + + # Initialize request argument(s) + attached_cluster = gke_multicloud_v1.AttachedCluster() + attached_cluster.platform_version = "platform_version_value" + attached_cluster.distribution = "distribution_value" + attached_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAttachedClusterRequest( + attached_cluster=attached_cluster, + ) + + # Make the request + operation = client.update_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py new file mode 100644 index 000000000000..e2854cc7dd0c --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAttachedCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_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 gke_multicloud_v1 + + +def sample_update_attached_cluster(): + # Create a client + client = gke_multicloud_v1.AttachedClustersClient() + + # Initialize request argument(s) + attached_cluster = gke_multicloud_v1.AttachedCluster() + attached_cluster.platform_version = "platform_version_value" + attached_cluster.distribution = "distribution_value" + attached_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAttachedClusterRequest( + attached_cluster=attached_cluster, + ) + + # Make the request + operation = client.update_attached_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py new file mode 100644 index 000000000000..be6bd6e71991 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAwsCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_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 gke_multicloud_v1 + + +async def sample_create_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + aws_cluster = gke_multicloud_v1.AwsCluster() + aws_cluster.networking.vpc_id = "vpc_id_value" + aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + aws_cluster.aws_region = "aws_region_value" + aws_cluster.control_plane.version = "version_value" + aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] + aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" + aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" + aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAwsClusterRequest( + parent="parent_value", + aws_cluster=aws_cluster, + aws_cluster_id="aws_cluster_id_value", + ) + + # Make the request + operation = client.create_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py new file mode 100644 index 000000000000..7b67dfa0e9da --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAwsCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_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 gke_multicloud_v1 + + +def sample_create_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + aws_cluster = gke_multicloud_v1.AwsCluster() + aws_cluster.networking.vpc_id = "vpc_id_value" + aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + aws_cluster.aws_region = "aws_region_value" + aws_cluster.control_plane.version = "version_value" + aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] + aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" + aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" + aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAwsClusterRequest( + parent="parent_value", + aws_cluster=aws_cluster, + aws_cluster_id="aws_cluster_id_value", + ) + + # Make the request + operation = client.create_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py new file mode 100644 index 000000000000..e00d6b4fcd4f --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAwsNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_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 gke_multicloud_v1 + + +async def sample_create_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + aws_node_pool = gke_multicloud_v1.AwsNodePool() + aws_node_pool.version = "version_value" + aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" + aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_node_pool.autoscaling.min_node_count = 1489 + aws_node_pool.autoscaling.max_node_count = 1491 + aws_node_pool.subnet_id = "subnet_id_value" + aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.CreateAwsNodePoolRequest( + parent="parent_value", + aws_node_pool=aws_node_pool, + aws_node_pool_id="aws_node_pool_id_value", + ) + + # Make the request + operation = client.create_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py new file mode 100644 index 000000000000..649220317513 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAwsNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_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 gke_multicloud_v1 + + +def sample_create_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + aws_node_pool = gke_multicloud_v1.AwsNodePool() + aws_node_pool.version = "version_value" + aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" + aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_node_pool.autoscaling.min_node_count = 1489 + aws_node_pool.autoscaling.max_node_count = 1491 + aws_node_pool.subnet_id = "subnet_id_value" + aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.CreateAwsNodePoolRequest( + parent="parent_value", + aws_node_pool=aws_node_pool, + aws_node_pool_id="aws_node_pool_id_value", + ) + + # Make the request + operation = client.create_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py new file mode 100644 index 000000000000..11f7b3d31c82 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAwsCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_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 gke_multicloud_v1 + + +async def sample_delete_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAwsClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py new file mode 100644 index 000000000000..da1f735bf176 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAwsCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_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 gke_multicloud_v1 + + +def sample_delete_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAwsClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py new file mode 100644 index 000000000000..e5307f87c3fa --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAwsNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_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 gke_multicloud_v1 + + +async def sample_delete_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAwsNodePoolRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py new file mode 100644 index 000000000000..92f7d4c6f658 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAwsNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_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 gke_multicloud_v1 + + +def sample_delete_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAwsNodePoolRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py new file mode 100644 index 000000000000..0c83d56f3c0d --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAwsAccessToken +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_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 gke_multicloud_v1 + + +async def sample_generate_aws_access_token(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAwsAccessTokenRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = await client.generate_aws_access_token(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py new file mode 100644 index 000000000000..be14e3b8d261 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAwsAccessToken +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_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 gke_multicloud_v1 + + +def sample_generate_aws_access_token(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAwsAccessTokenRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = client.generate_aws_access_token(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py new file mode 100644 index 000000000000..a3b9a7e4e299 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAwsClusterAgentToken +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_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 gke_multicloud_v1 + + +async def sample_generate_aws_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAwsClusterAgentTokenRequest( + aws_cluster="aws_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = await client.generate_aws_cluster_agent_token(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py new file mode 100644 index 000000000000..01d8c89476eb --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAwsClusterAgentToken +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_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 gke_multicloud_v1 + + +def sample_generate_aws_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAwsClusterAgentTokenRequest( + aws_cluster="aws_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = client.generate_aws_cluster_agent_token(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py new file mode 100644 index 000000000000..d9470ec7f6bc --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAwsCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_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 gke_multicloud_v1 + + +async def sample_get_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_aws_cluster(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py new file mode 100644 index 000000000000..85769c701dab --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAwsCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_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 gke_multicloud_v1 + + +def sample_get_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_aws_cluster(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py new file mode 100644 index 000000000000..6f731bd2767c --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAwsJsonWebKeys +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_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 gke_multicloud_v1 + + +async def sample_get_aws_json_web_keys(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsJsonWebKeysRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = await client.get_aws_json_web_keys(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py new file mode 100644 index 000000000000..61a988ed4d0f --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAwsJsonWebKeys +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_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 gke_multicloud_v1 + + +def sample_get_aws_json_web_keys(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsJsonWebKeysRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = client.get_aws_json_web_keys(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py new file mode 100644 index 000000000000..0e239d2d4dfa --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAwsNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_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 gke_multicloud_v1 + + +async def sample_get_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsNodePoolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_aws_node_pool(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py new file mode 100644 index 000000000000..b38d3a435f8d --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAwsNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_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 gke_multicloud_v1 + + +def sample_get_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsNodePoolRequest( + name="name_value", + ) + + # Make the request + response = client.get_aws_node_pool(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py new file mode 100644 index 000000000000..4f7f579d6fe4 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAwsOpenIdConfig +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_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 gke_multicloud_v1 + + +async def sample_get_aws_open_id_config(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsOpenIdConfigRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = await client.get_aws_open_id_config(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py new file mode 100644 index 000000000000..5e9f5832cb61 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAwsOpenIdConfig +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_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 gke_multicloud_v1 + + +def sample_get_aws_open_id_config(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsOpenIdConfigRequest( + aws_cluster="aws_cluster_value", + ) + + # Make the request + response = client.get_aws_open_id_config(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py new file mode 100644 index 000000000000..575495d24b13 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAwsServerConfig +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_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 gke_multicloud_v1 + + +async def sample_get_aws_server_config(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsServerConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_aws_server_config(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py new file mode 100644 index 000000000000..3c5599d28c0d --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAwsServerConfig +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_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 gke_multicloud_v1 + + +def sample_get_aws_server_config(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAwsServerConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_aws_server_config(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py new file mode 100644 index 000000000000..31168fe1b810 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAwsClusters +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_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 gke_multicloud_v1 + + +async def sample_list_aws_clusters(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAwsClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_aws_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py new file mode 100644 index 000000000000..a68f90e25840 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAwsClusters +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_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 gke_multicloud_v1 + + +def sample_list_aws_clusters(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAwsClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_aws_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py new file mode 100644 index 000000000000..4749bf7f5753 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAwsNodePools +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_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 gke_multicloud_v1 + + +async def sample_list_aws_node_pools(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAwsNodePoolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_aws_node_pools(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py new file mode 100644 index 000000000000..ffb0a4efc524 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAwsNodePools +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_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 gke_multicloud_v1 + + +def sample_list_aws_node_pools(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAwsNodePoolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_aws_node_pools(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py new file mode 100644 index 000000000000..1831c8ccfe7a --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RollbackAwsNodePoolUpdate +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_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 gke_multicloud_v1 + + +async def sample_rollback_aws_node_pool_update(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.RollbackAwsNodePoolUpdateRequest( + name="name_value", + ) + + # Make the request + operation = client.rollback_aws_node_pool_update(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py new file mode 100644 index 000000000000..e9c031e87a74 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RollbackAwsNodePoolUpdate +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_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 gke_multicloud_v1 + + +def sample_rollback_aws_node_pool_update(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.RollbackAwsNodePoolUpdateRequest( + name="name_value", + ) + + # Make the request + operation = client.rollback_aws_node_pool_update(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py new file mode 100644 index 000000000000..599830b6a8db --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAwsCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_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 gke_multicloud_v1 + + +async def sample_update_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + aws_cluster = gke_multicloud_v1.AwsCluster() + aws_cluster.networking.vpc_id = "vpc_id_value" + aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + aws_cluster.aws_region = "aws_region_value" + aws_cluster.control_plane.version = "version_value" + aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] + aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" + aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" + aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAwsClusterRequest( + aws_cluster=aws_cluster, + ) + + # Make the request + operation = client.update_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py new file mode 100644 index 000000000000..0d47bec19742 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAwsCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_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 gke_multicloud_v1 + + +def sample_update_aws_cluster(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + aws_cluster = gke_multicloud_v1.AwsCluster() + aws_cluster.networking.vpc_id = "vpc_id_value" + aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + aws_cluster.aws_region = "aws_region_value" + aws_cluster.control_plane.version = "version_value" + aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] + aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" + aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" + aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAwsClusterRequest( + aws_cluster=aws_cluster, + ) + + # Make the request + operation = client.update_aws_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py new file mode 100644 index 000000000000..5c336772653c --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAwsNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_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 gke_multicloud_v1 + + +async def sample_update_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersAsyncClient() + + # Initialize request argument(s) + aws_node_pool = gke_multicloud_v1.AwsNodePool() + aws_node_pool.version = "version_value" + aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" + aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_node_pool.autoscaling.min_node_count = 1489 + aws_node_pool.autoscaling.max_node_count = 1491 + aws_node_pool.subnet_id = "subnet_id_value" + aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.UpdateAwsNodePoolRequest( + aws_node_pool=aws_node_pool, + ) + + # Make the request + operation = client.update_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py new file mode 100644 index 000000000000..2e4fb0a3cc29 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAwsNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_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 gke_multicloud_v1 + + +def sample_update_aws_node_pool(): + # Create a client + client = gke_multicloud_v1.AwsClustersClient() + + # Initialize request argument(s) + aws_node_pool = gke_multicloud_v1.AwsNodePool() + aws_node_pool.version = "version_value" + aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" + aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" + aws_node_pool.autoscaling.min_node_count = 1489 + aws_node_pool.autoscaling.max_node_count = 1491 + aws_node_pool.subnet_id = "subnet_id_value" + aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.UpdateAwsNodePoolRequest( + aws_node_pool=aws_node_pool, + ) + + # Make the request + operation = client.update_aws_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py new file mode 100644 index 000000000000..d08247c0e32f --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAzureClient +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_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 gke_multicloud_v1 + + +async def sample_create_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + azure_client = gke_multicloud_v1.AzureClient() + azure_client.tenant_id = "tenant_id_value" + azure_client.application_id = "application_id_value" + + request = gke_multicloud_v1.CreateAzureClientRequest( + parent="parent_value", + azure_client=azure_client, + azure_client_id="azure_client_id_value", + ) + + # Make the request + operation = client.create_azure_client(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py new file mode 100644 index 000000000000..3de1be17e9e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAzureClient +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_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 gke_multicloud_v1 + + +def sample_create_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + azure_client = gke_multicloud_v1.AzureClient() + azure_client.tenant_id = "tenant_id_value" + azure_client.application_id = "application_id_value" + + request = gke_multicloud_v1.CreateAzureClientRequest( + parent="parent_value", + azure_client=azure_client, + azure_client_id="azure_client_id_value", + ) + + # Make the request + operation = client.create_azure_client(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py new file mode 100644 index 000000000000..8a83f88ae20b --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAzureCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_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 gke_multicloud_v1 + + +async def sample_create_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + azure_cluster = gke_multicloud_v1.AzureCluster() + azure_cluster.azure_region = "azure_region_value" + azure_cluster.resource_group_id = "resource_group_id_value" + azure_cluster.networking.virtual_network_id = "virtual_network_id_value" + azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + azure_cluster.control_plane.version = "version_value" + azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" + azure_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAzureClusterRequest( + parent="parent_value", + azure_cluster=azure_cluster, + azure_cluster_id="azure_cluster_id_value", + ) + + # Make the request + operation = client.create_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py new file mode 100644 index 000000000000..35f26bf00e4c --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAzureCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_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 gke_multicloud_v1 + + +def sample_create_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + azure_cluster = gke_multicloud_v1.AzureCluster() + azure_cluster.azure_region = "azure_region_value" + azure_cluster.resource_group_id = "resource_group_id_value" + azure_cluster.networking.virtual_network_id = "virtual_network_id_value" + azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + azure_cluster.control_plane.version = "version_value" + azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" + azure_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.CreateAzureClusterRequest( + parent="parent_value", + azure_cluster=azure_cluster, + azure_cluster_id="azure_cluster_id_value", + ) + + # Make the request + operation = client.create_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py new file mode 100644 index 000000000000..09cc4343d068 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAzureNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_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 gke_multicloud_v1 + + +async def sample_create_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + azure_node_pool = gke_multicloud_v1.AzureNodePool() + azure_node_pool.version = "version_value" + azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" + azure_node_pool.subnet_id = "subnet_id_value" + azure_node_pool.autoscaling.min_node_count = 1489 + azure_node_pool.autoscaling.max_node_count = 1491 + azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.CreateAzureNodePoolRequest( + parent="parent_value", + azure_node_pool=azure_node_pool, + azure_node_pool_id="azure_node_pool_id_value", + ) + + # Make the request + operation = client.create_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py new file mode 100644 index 000000000000..f88947000da6 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAzureNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_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 gke_multicloud_v1 + + +def sample_create_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + azure_node_pool = gke_multicloud_v1.AzureNodePool() + azure_node_pool.version = "version_value" + azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" + azure_node_pool.subnet_id = "subnet_id_value" + azure_node_pool.autoscaling.min_node_count = 1489 + azure_node_pool.autoscaling.max_node_count = 1491 + azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.CreateAzureNodePoolRequest( + parent="parent_value", + azure_node_pool=azure_node_pool, + azure_node_pool_id="azure_node_pool_id_value", + ) + + # Make the request + operation = client.create_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py new file mode 100644 index 000000000000..4e1c0ee35861 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAzureClient +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_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 gke_multicloud_v1 + + +async def sample_delete_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureClientRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_client(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py new file mode 100644 index 000000000000..ec3297977d12 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAzureClient +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_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 gke_multicloud_v1 + + +def sample_delete_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureClientRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_client(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py new file mode 100644 index 000000000000..96c20cdd55f1 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAzureCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_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 gke_multicloud_v1 + + +async def sample_delete_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py new file mode 100644 index 000000000000..0dd1750c9fe9 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAzureCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_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 gke_multicloud_v1 + + +def sample_delete_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py new file mode 100644 index 000000000000..af626d99ca9f --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAzureNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_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 gke_multicloud_v1 + + +async def sample_delete_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureNodePoolRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py new file mode 100644 index 000000000000..2e3b80e11752 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAzureNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_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 gke_multicloud_v1 + + +def sample_delete_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.DeleteAzureNodePoolRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py new file mode 100644 index 000000000000..c7f45cbacde2 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAzureAccessToken +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_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 gke_multicloud_v1 + + +async def sample_generate_azure_access_token(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAzureAccessTokenRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = await client.generate_azure_access_token(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py new file mode 100644 index 000000000000..4ca5ec07e9a6 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAzureAccessToken +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_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 gke_multicloud_v1 + + +def sample_generate_azure_access_token(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAzureAccessTokenRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = client.generate_azure_access_token(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py new file mode 100644 index 000000000000..77828cc130b0 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAzureClusterAgentToken +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_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 gke_multicloud_v1 + + +async def sample_generate_azure_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAzureClusterAgentTokenRequest( + azure_cluster="azure_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = await client.generate_azure_cluster_agent_token(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py new file mode 100644 index 000000000000..42e1f3278668 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAzureClusterAgentToken +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_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 gke_multicloud_v1 + + +def sample_generate_azure_cluster_agent_token(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GenerateAzureClusterAgentTokenRequest( + azure_cluster="azure_cluster_value", + subject_token="subject_token_value", + subject_token_type="subject_token_type_value", + version="version_value", + ) + + # Make the request + response = client.generate_azure_cluster_agent_token(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py new file mode 100644 index 000000000000..6443b3d16d37 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureClient +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureClient_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 gke_multicloud_v1 + + +async def sample_get_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureClientRequest( + name="name_value", + ) + + # Make the request + response = await client.get_azure_client(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureClient_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py new file mode 100644 index 000000000000..070a7f4ac0df --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureClient +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureClient_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 gke_multicloud_v1 + + +def sample_get_azure_client(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureClientRequest( + name="name_value", + ) + + # Make the request + response = client.get_azure_client(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureClient_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py new file mode 100644 index 000000000000..bab6585f3ce3 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_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 gke_multicloud_v1 + + +async def sample_get_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_azure_cluster(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py new file mode 100644 index 000000000000..20cfcf7ba59a --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_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 gke_multicloud_v1 + + +def sample_get_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_azure_cluster(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py new file mode 100644 index 000000000000..5e288213c015 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureJsonWebKeys +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_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 gke_multicloud_v1 + + +async def sample_get_azure_json_web_keys(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureJsonWebKeysRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = await client.get_azure_json_web_keys(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py new file mode 100644 index 000000000000..75e51160764d --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureJsonWebKeys +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_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 gke_multicloud_v1 + + +def sample_get_azure_json_web_keys(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureJsonWebKeysRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = client.get_azure_json_web_keys(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py new file mode 100644 index 000000000000..f1bdfe5372ee --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_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 gke_multicloud_v1 + + +async def sample_get_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureNodePoolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_azure_node_pool(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py new file mode 100644 index 000000000000..1a6852417a82 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_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 gke_multicloud_v1 + + +def sample_get_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureNodePoolRequest( + name="name_value", + ) + + # Make the request + response = client.get_azure_node_pool(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py new file mode 100644 index 000000000000..27154b26d7cd --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureOpenIdConfig +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_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 gke_multicloud_v1 + + +async def sample_get_azure_open_id_config(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureOpenIdConfigRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = await client.get_azure_open_id_config(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py new file mode 100644 index 000000000000..a1a893e498b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureOpenIdConfig +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_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 gke_multicloud_v1 + + +def sample_get_azure_open_id_config(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureOpenIdConfigRequest( + azure_cluster="azure_cluster_value", + ) + + # Make the request + response = client.get_azure_open_id_config(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py new file mode 100644 index 000000000000..a8977ab891c4 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureServerConfig +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_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 gke_multicloud_v1 + + +async def sample_get_azure_server_config(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureServerConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_azure_server_config(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py new file mode 100644 index 000000000000..bec52cb720fe --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAzureServerConfig +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_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 gke_multicloud_v1 + + +def sample_get_azure_server_config(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.GetAzureServerConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_azure_server_config(request=request) + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py new file mode 100644 index 000000000000..c34a6bdd6b86 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAzureClients +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_ListAzureClients_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 gke_multicloud_v1 + + +async def sample_list_azure_clients(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureClientsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_clients(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_ListAzureClients_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py new file mode 100644 index 000000000000..2428b5587882 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAzureClients +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_ListAzureClients_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 gke_multicloud_v1 + + +def sample_list_azure_clients(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureClientsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_clients(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_ListAzureClients_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py new file mode 100644 index 000000000000..a9eb485ba74a --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAzureClusters +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_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 gke_multicloud_v1 + + +async def sample_list_azure_clusters(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py new file mode 100644 index 000000000000..19ddcdc67662 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAzureClusters +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_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 gke_multicloud_v1 + + +def sample_list_azure_clusters(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py new file mode 100644 index 000000000000..2f119291ad50 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAzureNodePools +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_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 gke_multicloud_v1 + + +async def sample_list_azure_node_pools(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureNodePoolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_node_pools(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py new file mode 100644 index 000000000000..48887c75dec4 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAzureNodePools +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_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 gke_multicloud_v1 + + +def sample_list_azure_node_pools(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + request = gke_multicloud_v1.ListAzureNodePoolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_azure_node_pools(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py new file mode 100644 index 000000000000..66b255ccfc27 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAzureCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_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 gke_multicloud_v1 + + +async def sample_update_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + azure_cluster = gke_multicloud_v1.AzureCluster() + azure_cluster.azure_region = "azure_region_value" + azure_cluster.resource_group_id = "resource_group_id_value" + azure_cluster.networking.virtual_network_id = "virtual_network_id_value" + azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + azure_cluster.control_plane.version = "version_value" + azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" + azure_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAzureClusterRequest( + azure_cluster=azure_cluster, + ) + + # Make the request + operation = client.update_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py new file mode 100644 index 000000000000..96ee39a51052 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAzureCluster +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_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 gke_multicloud_v1 + + +def sample_update_azure_cluster(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + azure_cluster = gke_multicloud_v1.AzureCluster() + azure_cluster.azure_region = "azure_region_value" + azure_cluster.resource_group_id = "resource_group_id_value" + azure_cluster.networking.virtual_network_id = "virtual_network_id_value" + azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] + azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] + azure_cluster.control_plane.version = "version_value" + azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" + azure_cluster.fleet.project = "project_value" + + request = gke_multicloud_v1.UpdateAzureClusterRequest( + azure_cluster=azure_cluster, + ) + + # Make the request + operation = client.update_azure_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py new file mode 100644 index 000000000000..b5973a6d4fc3 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAzureNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_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 gke_multicloud_v1 + + +async def sample_update_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersAsyncClient() + + # Initialize request argument(s) + azure_node_pool = gke_multicloud_v1.AzureNodePool() + azure_node_pool.version = "version_value" + azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" + azure_node_pool.subnet_id = "subnet_id_value" + azure_node_pool.autoscaling.min_node_count = 1489 + azure_node_pool.autoscaling.max_node_count = 1491 + azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.UpdateAzureNodePoolRequest( + azure_node_pool=azure_node_pool, + ) + + # Make the request + operation = client.update_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py new file mode 100644 index 000000000000..d3e42f5ebc82 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAzureNodePool +# 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-multicloud + + +# [START gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_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 gke_multicloud_v1 + + +def sample_update_azure_node_pool(): + # Create a client + client = gke_multicloud_v1.AzureClustersClient() + + # Initialize request argument(s) + azure_node_pool = gke_multicloud_v1.AzureNodePool() + azure_node_pool.version = "version_value" + azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" + azure_node_pool.subnet_id = "subnet_id_value" + azure_node_pool.autoscaling.min_node_count = 1489 + azure_node_pool.autoscaling.max_node_count = 1491 + azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 + + request = gke_multicloud_v1.UpdateAzureNodePoolRequest( + azure_node_pool=azure_node_pool, + ) + + # Make the request + operation = client.update_azure_node_pool(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json new file mode 100644 index 000000000000..34b757edefd0 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json @@ -0,0 +1,7195 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.gkemulticloud.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-gke-multicloud", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", + "shortName": "AttachedClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.create_attached_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.CreateAttachedCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "CreateAttachedCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAttachedClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "attached_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AttachedCluster" + }, + { + "name": "attached_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_attached_cluster" + }, + "description": "Sample for CreateAttachedCluster", + "file": "gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", + "shortName": "AttachedClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.create_attached_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.CreateAttachedCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "CreateAttachedCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAttachedClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "attached_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AttachedCluster" + }, + { + "name": "attached_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_attached_cluster" + }, + "description": "Sample for CreateAttachedCluster", + "file": "gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", + "shortName": "AttachedClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.delete_attached_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.DeleteAttachedCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "DeleteAttachedCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAttachedClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_attached_cluster" + }, + "description": "Sample for DeleteAttachedCluster", + "file": "gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_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": "gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", + "shortName": "AttachedClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.delete_attached_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.DeleteAttachedCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "DeleteAttachedCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAttachedClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_attached_cluster" + }, + "description": "Sample for DeleteAttachedCluster", + "file": "gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_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": "gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", + "shortName": "AttachedClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.generate_attached_cluster_agent_token", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GenerateAttachedClusterAgentToken", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "GenerateAttachedClusterAgentToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenResponse", + "shortName": "generate_attached_cluster_agent_token" + }, + "description": "Sample for GenerateAttachedClusterAgentToken", + "file": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", + "shortName": "AttachedClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.generate_attached_cluster_agent_token", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GenerateAttachedClusterAgentToken", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "GenerateAttachedClusterAgentToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenResponse", + "shortName": "generate_attached_cluster_agent_token" + }, + "description": "Sample for GenerateAttachedClusterAgentToken", + "file": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", + "shortName": "AttachedClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.generate_attached_cluster_install_manifest", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GenerateAttachedClusterInstallManifest", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "GenerateAttachedClusterInstallManifest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "attached_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestResponse", + "shortName": "generate_attached_cluster_install_manifest" + }, + "description": "Sample for GenerateAttachedClusterInstallManifest", + "file": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", + "shortName": "AttachedClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.generate_attached_cluster_install_manifest", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GenerateAttachedClusterInstallManifest", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "GenerateAttachedClusterInstallManifest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "attached_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestResponse", + "shortName": "generate_attached_cluster_install_manifest" + }, + "description": "Sample for GenerateAttachedClusterInstallManifest", + "file": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", + "shortName": "AttachedClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.get_attached_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "GetAttachedCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAttachedClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AttachedCluster", + "shortName": "get_attached_cluster" + }, + "description": "Sample for GetAttachedCluster", + "file": "gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_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": "gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", + "shortName": "AttachedClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.get_attached_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "GetAttachedCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAttachedClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AttachedCluster", + "shortName": "get_attached_cluster" + }, + "description": "Sample for GetAttachedCluster", + "file": "gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_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": "gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", + "shortName": "AttachedClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.get_attached_server_config", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedServerConfig", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "GetAttachedServerConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAttachedServerConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AttachedServerConfig", + "shortName": "get_attached_server_config" + }, + "description": "Sample for GetAttachedServerConfig", + "file": "gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_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": "gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", + "shortName": "AttachedClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.get_attached_server_config", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedServerConfig", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "GetAttachedServerConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAttachedServerConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AttachedServerConfig", + "shortName": "get_attached_server_config" + }, + "description": "Sample for GetAttachedServerConfig", + "file": "gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_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": "gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", + "shortName": "AttachedClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.import_attached_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.ImportAttachedCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "ImportAttachedCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ImportAttachedClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "fleet_membership", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_attached_cluster" + }, + "description": "Sample for ImportAttachedCluster", + "file": "gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", + "shortName": "AttachedClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.import_attached_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.ImportAttachedCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "ImportAttachedCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ImportAttachedClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "fleet_membership", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_attached_cluster" + }, + "description": "Sample for ImportAttachedCluster", + "file": "gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", + "shortName": "AttachedClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.list_attached_clusters", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.ListAttachedClusters", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "ListAttachedClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.attached_clusters.pagers.ListAttachedClustersAsyncPager", + "shortName": "list_attached_clusters" + }, + "description": "Sample for ListAttachedClusters", + "file": "gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_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": "gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", + "shortName": "AttachedClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.list_attached_clusters", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.ListAttachedClusters", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "ListAttachedClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.attached_clusters.pagers.ListAttachedClustersPager", + "shortName": "list_attached_clusters" + }, + "description": "Sample for ListAttachedClusters", + "file": "gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_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": "gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", + "shortName": "AttachedClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.update_attached_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.UpdateAttachedCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "UpdateAttachedCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.UpdateAttachedClusterRequest" + }, + { + "name": "attached_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AttachedCluster" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_attached_cluster" + }, + "description": "Sample for UpdateAttachedCluster", + "file": "gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", + "shortName": "AttachedClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.update_attached_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.UpdateAttachedCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", + "shortName": "AttachedClusters" + }, + "shortName": "UpdateAttachedCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.UpdateAttachedClusterRequest" + }, + { + "name": "attached_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AttachedCluster" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_attached_cluster" + }, + "description": "Sample for UpdateAttachedCluster", + "file": "gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.create_aws_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.CreateAwsCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "CreateAwsCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAwsClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "aws_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AwsCluster" + }, + { + "name": "aws_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_aws_cluster" + }, + "description": "Sample for CreateAwsCluster", + "file": "gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_async", + "segments": [ + { + "end": 70, + "start": 27, + "type": "FULL" + }, + { + "end": 70, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 60, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 67, + "start": 61, + "type": "REQUEST_EXECUTION" + }, + { + "end": 71, + "start": 68, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.create_aws_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.CreateAwsCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "CreateAwsCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAwsClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "aws_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AwsCluster" + }, + { + "name": "aws_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_aws_cluster" + }, + "description": "Sample for CreateAwsCluster", + "file": "gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_sync", + "segments": [ + { + "end": 70, + "start": 27, + "type": "FULL" + }, + { + "end": 70, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 60, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 67, + "start": 61, + "type": "REQUEST_EXECUTION" + }, + { + "end": 71, + "start": 68, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.create_aws_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.CreateAwsNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "CreateAwsNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAwsNodePoolRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "aws_node_pool", + "type": "google.cloud.gke_multicloud_v1.types.AwsNodePool" + }, + { + "name": "aws_node_pool_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_aws_node_pool" + }, + "description": "Sample for CreateAwsNodePool", + "file": "gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_async", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 56, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 63, + "start": 57, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 64, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.create_aws_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.CreateAwsNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "CreateAwsNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAwsNodePoolRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "aws_node_pool", + "type": "google.cloud.gke_multicloud_v1.types.AwsNodePool" + }, + { + "name": "aws_node_pool_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_aws_node_pool" + }, + "description": "Sample for CreateAwsNodePool", + "file": "gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_sync", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 56, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 63, + "start": 57, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 64, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.delete_aws_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.DeleteAwsCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "DeleteAwsCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAwsClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_aws_cluster" + }, + "description": "Sample for DeleteAwsCluster", + "file": "gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_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": "gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.delete_aws_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.DeleteAwsCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "DeleteAwsCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAwsClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_aws_cluster" + }, + "description": "Sample for DeleteAwsCluster", + "file": "gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_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": "gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.delete_aws_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.DeleteAwsNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "DeleteAwsNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAwsNodePoolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_aws_node_pool" + }, + "description": "Sample for DeleteAwsNodePool", + "file": "gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_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": "gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.delete_aws_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.DeleteAwsNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "DeleteAwsNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAwsNodePoolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_aws_node_pool" + }, + "description": "Sample for DeleteAwsNodePool", + "file": "gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_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": "gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.generate_aws_access_token", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GenerateAwsAccessToken", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GenerateAwsAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenResponse", + "shortName": "generate_aws_access_token" + }, + "description": "Sample for GenerateAwsAccessToken", + "file": "gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_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": "gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.generate_aws_access_token", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GenerateAwsAccessToken", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GenerateAwsAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenResponse", + "shortName": "generate_aws_access_token" + }, + "description": "Sample for GenerateAwsAccessToken", + "file": "gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_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": "gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.generate_aws_cluster_agent_token", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GenerateAwsClusterAgentToken", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GenerateAwsClusterAgentToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenResponse", + "shortName": "generate_aws_cluster_agent_token" + }, + "description": "Sample for GenerateAwsClusterAgentToken", + "file": "gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.generate_aws_cluster_agent_token", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GenerateAwsClusterAgentToken", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GenerateAwsClusterAgentToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenResponse", + "shortName": "generate_aws_cluster_agent_token" + }, + "description": "Sample for GenerateAwsClusterAgentToken", + "file": "gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.get_aws_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GetAwsCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAwsClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AwsCluster", + "shortName": "get_aws_cluster" + }, + "description": "Sample for GetAwsCluster", + "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.get_aws_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GetAwsCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAwsClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AwsCluster", + "shortName": "get_aws_cluster" + }, + "description": "Sample for GetAwsCluster", + "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.get_aws_json_web_keys", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsJsonWebKeys", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GetAwsJsonWebKeys" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAwsJsonWebKeysRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AwsJsonWebKeys", + "shortName": "get_aws_json_web_keys" + }, + "description": "Sample for GetAwsJsonWebKeys", + "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.get_aws_json_web_keys", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsJsonWebKeys", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GetAwsJsonWebKeys" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAwsJsonWebKeysRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AwsJsonWebKeys", + "shortName": "get_aws_json_web_keys" + }, + "description": "Sample for GetAwsJsonWebKeys", + "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.get_aws_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GetAwsNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAwsNodePoolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AwsNodePool", + "shortName": "get_aws_node_pool" + }, + "description": "Sample for GetAwsNodePool", + "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.get_aws_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GetAwsNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAwsNodePoolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AwsNodePool", + "shortName": "get_aws_node_pool" + }, + "description": "Sample for GetAwsNodePool", + "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.get_aws_open_id_config", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsOpenIdConfig", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GetAwsOpenIdConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAwsOpenIdConfigRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AwsOpenIdConfig", + "shortName": "get_aws_open_id_config" + }, + "description": "Sample for GetAwsOpenIdConfig", + "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.get_aws_open_id_config", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsOpenIdConfig", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GetAwsOpenIdConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAwsOpenIdConfigRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AwsOpenIdConfig", + "shortName": "get_aws_open_id_config" + }, + "description": "Sample for GetAwsOpenIdConfig", + "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.get_aws_server_config", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsServerConfig", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GetAwsServerConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAwsServerConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AwsServerConfig", + "shortName": "get_aws_server_config" + }, + "description": "Sample for GetAwsServerConfig", + "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.get_aws_server_config", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsServerConfig", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "GetAwsServerConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAwsServerConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AwsServerConfig", + "shortName": "get_aws_server_config" + }, + "description": "Sample for GetAwsServerConfig", + "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.list_aws_clusters", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.ListAwsClusters", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "ListAwsClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsClustersAsyncPager", + "shortName": "list_aws_clusters" + }, + "description": "Sample for ListAwsClusters", + "file": "gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_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": "gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.list_aws_clusters", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.ListAwsClusters", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "ListAwsClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsClustersPager", + "shortName": "list_aws_clusters" + }, + "description": "Sample for ListAwsClusters", + "file": "gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_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": "gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.list_aws_node_pools", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.ListAwsNodePools", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "ListAwsNodePools" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsNodePoolsAsyncPager", + "shortName": "list_aws_node_pools" + }, + "description": "Sample for ListAwsNodePools", + "file": "gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_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": "gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.list_aws_node_pools", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.ListAwsNodePools", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "ListAwsNodePools" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsNodePoolsPager", + "shortName": "list_aws_node_pools" + }, + "description": "Sample for ListAwsNodePools", + "file": "gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_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": "gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.rollback_aws_node_pool_update", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.RollbackAwsNodePoolUpdate", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "RollbackAwsNodePoolUpdate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.RollbackAwsNodePoolUpdateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "rollback_aws_node_pool_update" + }, + "description": "Sample for RollbackAwsNodePoolUpdate", + "file": "gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_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": "gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.rollback_aws_node_pool_update", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.RollbackAwsNodePoolUpdate", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "RollbackAwsNodePoolUpdate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.RollbackAwsNodePoolUpdateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "rollback_aws_node_pool_update" + }, + "description": "Sample for RollbackAwsNodePoolUpdate", + "file": "gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_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": "gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.update_aws_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.UpdateAwsCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "UpdateAwsCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.UpdateAwsClusterRequest" + }, + { + "name": "aws_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AwsCluster" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_aws_cluster" + }, + "description": "Sample for UpdateAwsCluster", + "file": "gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_async", + "segments": [ + { + "end": 68, + "start": 27, + "type": "FULL" + }, + { + "end": 68, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 58, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 65, + "start": 59, + "type": "REQUEST_EXECUTION" + }, + { + "end": 69, + "start": 66, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.update_aws_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.UpdateAwsCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "UpdateAwsCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.UpdateAwsClusterRequest" + }, + { + "name": "aws_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AwsCluster" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_aws_cluster" + }, + "description": "Sample for UpdateAwsCluster", + "file": "gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_sync", + "segments": [ + { + "end": 68, + "start": 27, + "type": "FULL" + }, + { + "end": 68, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 58, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 65, + "start": 59, + "type": "REQUEST_EXECUTION" + }, + { + "end": 69, + "start": 66, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", + "shortName": "AwsClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.update_aws_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.UpdateAwsNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "UpdateAwsNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.UpdateAwsNodePoolRequest" + }, + { + "name": "aws_node_pool", + "type": "google.cloud.gke_multicloud_v1.types.AwsNodePool" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_aws_node_pool" + }, + "description": "Sample for UpdateAwsNodePool", + "file": "gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_async", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", + "shortName": "AwsClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.update_aws_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.UpdateAwsNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", + "shortName": "AwsClusters" + }, + "shortName": "UpdateAwsNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.UpdateAwsNodePoolRequest" + }, + { + "name": "aws_node_pool", + "type": "google.cloud.gke_multicloud_v1.types.AwsNodePool" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_aws_node_pool" + }, + "description": "Sample for UpdateAwsNodePool", + "file": "gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_sync", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.create_azure_client", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureClient", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "CreateAzureClient" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAzureClientRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "azure_client", + "type": "google.cloud.gke_multicloud_v1.types.AzureClient" + }, + { + "name": "azure_client_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_azure_client" + }, + "description": "Sample for CreateAzureClient", + "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.create_azure_client", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureClient", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "CreateAzureClient" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAzureClientRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "azure_client", + "type": "google.cloud.gke_multicloud_v1.types.AzureClient" + }, + { + "name": "azure_client_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_azure_client" + }, + "description": "Sample for CreateAzureClient", + "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.create_azure_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "CreateAzureCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAzureClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "azure_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AzureCluster" + }, + { + "name": "azure_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_azure_cluster" + }, + "description": "Sample for CreateAzureCluster", + "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_async", + "segments": [ + { + "end": 67, + "start": 27, + "type": "FULL" + }, + { + "end": 67, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 57, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 64, + "start": 58, + "type": "REQUEST_EXECUTION" + }, + { + "end": 68, + "start": 65, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.create_azure_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "CreateAzureCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAzureClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "azure_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AzureCluster" + }, + { + "name": "azure_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_azure_cluster" + }, + "description": "Sample for CreateAzureCluster", + "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_sync", + "segments": [ + { + "end": 67, + "start": 27, + "type": "FULL" + }, + { + "end": 67, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 57, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 64, + "start": 58, + "type": "REQUEST_EXECUTION" + }, + { + "end": 68, + "start": 65, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.create_azure_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "CreateAzureNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAzureNodePoolRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "azure_node_pool", + "type": "google.cloud.gke_multicloud_v1.types.AzureNodePool" + }, + { + "name": "azure_node_pool_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_azure_node_pool" + }, + "description": "Sample for CreateAzureNodePool", + "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_async", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.create_azure_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "CreateAzureNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.CreateAzureNodePoolRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "azure_node_pool", + "type": "google.cloud.gke_multicloud_v1.types.AzureNodePool" + }, + { + "name": "azure_node_pool_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_azure_node_pool" + }, + "description": "Sample for CreateAzureNodePool", + "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_sync", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.delete_azure_client", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureClient", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "DeleteAzureClient" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureClientRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_azure_client" + }, + "description": "Sample for DeleteAzureClient", + "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.delete_azure_client", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureClient", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "DeleteAzureClient" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureClientRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_azure_client" + }, + "description": "Sample for DeleteAzureClient", + "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.delete_azure_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "DeleteAzureCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_azure_cluster" + }, + "description": "Sample for DeleteAzureCluster", + "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.delete_azure_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "DeleteAzureCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_azure_cluster" + }, + "description": "Sample for DeleteAzureCluster", + "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.delete_azure_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "DeleteAzureNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureNodePoolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_azure_node_pool" + }, + "description": "Sample for DeleteAzureNodePool", + "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.delete_azure_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "DeleteAzureNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureNodePoolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_azure_node_pool" + }, + "description": "Sample for DeleteAzureNodePool", + "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.generate_azure_access_token", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GenerateAzureAccessToken", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GenerateAzureAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenResponse", + "shortName": "generate_azure_access_token" + }, + "description": "Sample for GenerateAzureAccessToken", + "file": "gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_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": "gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.generate_azure_access_token", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GenerateAzureAccessToken", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GenerateAzureAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenResponse", + "shortName": "generate_azure_access_token" + }, + "description": "Sample for GenerateAzureAccessToken", + "file": "gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_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": "gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.generate_azure_cluster_agent_token", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GenerateAzureClusterAgentToken", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GenerateAzureClusterAgentToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenResponse", + "shortName": "generate_azure_cluster_agent_token" + }, + "description": "Sample for GenerateAzureClusterAgentToken", + "file": "gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.generate_azure_cluster_agent_token", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GenerateAzureClusterAgentToken", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GenerateAzureClusterAgentToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenResponse", + "shortName": "generate_azure_cluster_agent_token" + }, + "description": "Sample for GenerateAzureClusterAgentToken", + "file": "gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_client", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureClient", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureClient" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureClientRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureClient", + "shortName": "get_azure_client" + }, + "description": "Sample for GetAzureClient", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureClient_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_client", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureClient", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureClient" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureClientRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureClient", + "shortName": "get_azure_client" + }, + "description": "Sample for GetAzureClient", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureClient_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureCluster", + "shortName": "get_azure_cluster" + }, + "description": "Sample for GetAzureCluster", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureCluster", + "shortName": "get_azure_cluster" + }, + "description": "Sample for GetAzureCluster", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_json_web_keys", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureJsonWebKeys", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureJsonWebKeys" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureJsonWebKeysRequest" + }, + { + "name": "azure_cluster", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureJsonWebKeys", + "shortName": "get_azure_json_web_keys" + }, + "description": "Sample for GetAzureJsonWebKeys", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_json_web_keys", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureJsonWebKeys", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureJsonWebKeys" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureJsonWebKeysRequest" + }, + { + "name": "azure_cluster", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureJsonWebKeys", + "shortName": "get_azure_json_web_keys" + }, + "description": "Sample for GetAzureJsonWebKeys", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureNodePoolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureNodePool", + "shortName": "get_azure_node_pool" + }, + "description": "Sample for GetAzureNodePool", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureNodePoolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureNodePool", + "shortName": "get_azure_node_pool" + }, + "description": "Sample for GetAzureNodePool", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_open_id_config", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureOpenIdConfig", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureOpenIdConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureOpenIdConfigRequest" + }, + { + "name": "azure_cluster", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureOpenIdConfig", + "shortName": "get_azure_open_id_config" + }, + "description": "Sample for GetAzureOpenIdConfig", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_open_id_config", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureOpenIdConfig", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureOpenIdConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureOpenIdConfigRequest" + }, + { + "name": "azure_cluster", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureOpenIdConfig", + "shortName": "get_azure_open_id_config" + }, + "description": "Sample for GetAzureOpenIdConfig", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_server_config", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureServerConfig", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureServerConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureServerConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureServerConfig", + "shortName": "get_azure_server_config" + }, + "description": "Sample for GetAzureServerConfig", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_server_config", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureServerConfig", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "GetAzureServerConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.GetAzureServerConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.types.AzureServerConfig", + "shortName": "get_azure_server_config" + }, + "description": "Sample for GetAzureServerConfig", + "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.list_azure_clients", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClients", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "ListAzureClients" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClientsAsyncPager", + "shortName": "list_azure_clients" + }, + "description": "Sample for ListAzureClients", + "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureClients_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.list_azure_clients", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClients", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "ListAzureClients" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClientsPager", + "shortName": "list_azure_clients" + }, + "description": "Sample for ListAzureClients", + "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureClients_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.list_azure_clusters", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClusters", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "ListAzureClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClustersAsyncPager", + "shortName": "list_azure_clusters" + }, + "description": "Sample for ListAzureClusters", + "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.list_azure_clusters", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClusters", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "ListAzureClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClustersPager", + "shortName": "list_azure_clusters" + }, + "description": "Sample for ListAzureClusters", + "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.list_azure_node_pools", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureNodePools", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "ListAzureNodePools" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureNodePoolsAsyncPager", + "shortName": "list_azure_node_pools" + }, + "description": "Sample for ListAzureNodePools", + "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.list_azure_node_pools", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureNodePools", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "ListAzureNodePools" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureNodePoolsPager", + "shortName": "list_azure_node_pools" + }, + "description": "Sample for ListAzureNodePools", + "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.update_azure_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.UpdateAzureCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "UpdateAzureCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.UpdateAzureClusterRequest" + }, + { + "name": "azure_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AzureCluster" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_azure_cluster" + }, + "description": "Sample for UpdateAzureCluster", + "file": "gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_async", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.update_azure_cluster", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.UpdateAzureCluster", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "UpdateAzureCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.UpdateAzureClusterRequest" + }, + { + "name": "azure_cluster", + "type": "google.cloud.gke_multicloud_v1.types.AzureCluster" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_azure_cluster" + }, + "description": "Sample for UpdateAzureCluster", + "file": "gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_sync", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", + "shortName": "AzureClustersAsyncClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.update_azure_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.UpdateAzureNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "UpdateAzureNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.UpdateAzureNodePoolRequest" + }, + { + "name": "azure_node_pool", + "type": "google.cloud.gke_multicloud_v1.types.AzureNodePool" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_azure_node_pool" + }, + "description": "Sample for UpdateAzureNodePool", + "file": "gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_async", + "segments": [ + { + "end": 63, + "start": 27, + "type": "FULL" + }, + { + "end": 63, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 60, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 64, + "start": 61, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", + "shortName": "AzureClustersClient" + }, + "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.update_azure_node_pool", + "method": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.UpdateAzureNodePool", + "service": { + "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", + "shortName": "AzureClusters" + }, + "shortName": "UpdateAzureNodePool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gke_multicloud_v1.types.UpdateAzureNodePoolRequest" + }, + { + "name": "azure_node_pool", + "type": "google.cloud.gke_multicloud_v1.types.AzureNodePool" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_azure_node_pool" + }, + "description": "Sample for UpdateAzureNodePool", + "file": "gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_sync", + "segments": [ + { + "end": 63, + "start": 27, + "type": "FULL" + }, + { + "end": 63, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 60, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 64, + "start": 61, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/scripts/fixup_gke_multicloud_v1_keywords.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/scripts/fixup_gke_multicloud_v1_keywords.py new file mode 100644 index 000000000000..cd48868cf598 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/scripts/fixup_gke_multicloud_v1_keywords.py @@ -0,0 +1,219 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class gke_multicloudCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_attached_cluster': ('parent', 'attached_cluster', 'attached_cluster_id', 'validate_only', ), + 'create_aws_cluster': ('parent', 'aws_cluster', 'aws_cluster_id', 'validate_only', ), + 'create_aws_node_pool': ('parent', 'aws_node_pool', 'aws_node_pool_id', 'validate_only', ), + 'create_azure_client': ('parent', 'azure_client', 'azure_client_id', 'validate_only', ), + 'create_azure_cluster': ('parent', 'azure_cluster', 'azure_cluster_id', 'validate_only', ), + 'create_azure_node_pool': ('parent', 'azure_node_pool', 'azure_node_pool_id', 'validate_only', ), + 'delete_attached_cluster': ('name', 'validate_only', 'allow_missing', 'ignore_errors', 'etag', ), + 'delete_aws_cluster': ('name', 'validate_only', 'allow_missing', 'ignore_errors', 'etag', ), + 'delete_aws_node_pool': ('name', 'validate_only', 'allow_missing', 'ignore_errors', 'etag', ), + 'delete_azure_client': ('name', 'allow_missing', 'validate_only', ), + 'delete_azure_cluster': ('name', 'allow_missing', 'validate_only', 'etag', 'ignore_errors', ), + 'delete_azure_node_pool': ('name', 'validate_only', 'allow_missing', 'etag', 'ignore_errors', ), + 'generate_attached_cluster_agent_token': ('attached_cluster', 'subject_token', 'subject_token_type', 'version', 'grant_type', 'audience', 'scope', 'requested_token_type', 'options', ), + 'generate_attached_cluster_install_manifest': ('parent', 'attached_cluster_id', 'platform_version', 'proxy_config', ), + 'generate_aws_access_token': ('aws_cluster', ), + 'generate_aws_cluster_agent_token': ('aws_cluster', 'subject_token', 'subject_token_type', 'version', 'node_pool_id', 'grant_type', 'audience', 'scope', 'requested_token_type', 'options', ), + 'generate_azure_access_token': ('azure_cluster', ), + 'generate_azure_cluster_agent_token': ('azure_cluster', 'subject_token', 'subject_token_type', 'version', 'node_pool_id', 'grant_type', 'audience', 'scope', 'requested_token_type', 'options', ), + 'get_attached_cluster': ('name', ), + 'get_attached_server_config': ('name', ), + 'get_aws_cluster': ('name', ), + 'get_aws_json_web_keys': ('aws_cluster', ), + 'get_aws_node_pool': ('name', ), + 'get_aws_open_id_config': ('aws_cluster', ), + 'get_aws_server_config': ('name', ), + 'get_azure_client': ('name', ), + 'get_azure_cluster': ('name', ), + 'get_azure_json_web_keys': ('azure_cluster', ), + 'get_azure_node_pool': ('name', ), + 'get_azure_open_id_config': ('azure_cluster', ), + 'get_azure_server_config': ('name', ), + 'import_attached_cluster': ('parent', 'fleet_membership', 'platform_version', 'distribution', 'validate_only', 'proxy_config', ), + 'list_attached_clusters': ('parent', 'page_size', 'page_token', ), + 'list_aws_clusters': ('parent', 'page_size', 'page_token', ), + 'list_aws_node_pools': ('parent', 'page_size', 'page_token', ), + 'list_azure_clients': ('parent', 'page_size', 'page_token', ), + 'list_azure_clusters': ('parent', 'page_size', 'page_token', ), + 'list_azure_node_pools': ('parent', 'page_size', 'page_token', ), + 'rollback_aws_node_pool_update': ('name', 'respect_pdb', ), + 'update_attached_cluster': ('attached_cluster', 'update_mask', 'validate_only', ), + 'update_aws_cluster': ('aws_cluster', 'update_mask', 'validate_only', ), + 'update_aws_node_pool': ('aws_node_pool', 'update_mask', 'validate_only', ), + 'update_azure_cluster': ('azure_cluster', 'update_mask', 'validate_only', ), + 'update_azure_node_pool': ('azure_node_pool', 'update_mask', 'validate_only', ), + } + + 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=gke_multicloudCallTransformer(), +): + """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 gke_multicloud client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/setup.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/setup.py new file mode 100644 index 000000000000..e3eb68074546 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/setup.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-gke-multicloud' + + +description = "Google Cloud Gke Multicloud API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/gke_multicloud/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-multicloud" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/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/google-cloud-gke-multicloud/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/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/google-cloud-gke-multicloud/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/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/google-cloud-gke-multicloud/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.13.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/google-cloud-gke-multicloud/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/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.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/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/google-cloud-gke-multicloud/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/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/google-cloud-gke-multicloud/v1/tests/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_attached_clusters.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_attached_clusters.py new file mode 100644 index 000000000000..e446f56b4f3f --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_attached_clusters.py @@ -0,0 +1,8616 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.gke_multicloud_v1.services.attached_clusters import AttachedClustersAsyncClient +from google.cloud.gke_multicloud_v1.services.attached_clusters import AttachedClustersClient +from google.cloud.gke_multicloud_v1.services.attached_clusters import pagers +from google.cloud.gke_multicloud_v1.services.attached_clusters import transports +from google.cloud.gke_multicloud_v1.types import attached_resources +from google.cloud.gke_multicloud_v1.types import attached_service +from google.cloud.gke_multicloud_v1.types import common_resources +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 + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AttachedClustersClient._get_default_mtls_endpoint(None) is None + assert AttachedClustersClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AttachedClustersClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AttachedClustersClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AttachedClustersClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AttachedClustersClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AttachedClustersClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AttachedClustersClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AttachedClustersClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AttachedClustersClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert AttachedClustersClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AttachedClustersClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AttachedClustersClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AttachedClustersClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert AttachedClustersClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert AttachedClustersClient._get_client_cert_source(None, False) is None + assert AttachedClustersClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AttachedClustersClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert AttachedClustersClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AttachedClustersClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AttachedClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersClient)) +@mock.patch.object(AttachedClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AttachedClustersClient._DEFAULT_UNIVERSE + default_endpoint = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AttachedClustersClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AttachedClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AttachedClustersClient.DEFAULT_MTLS_ENDPOINT + assert AttachedClustersClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AttachedClustersClient._get_api_endpoint(None, None, default_universe, "always") == AttachedClustersClient.DEFAULT_MTLS_ENDPOINT + assert AttachedClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AttachedClustersClient.DEFAULT_MTLS_ENDPOINT + assert AttachedClustersClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AttachedClustersClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AttachedClustersClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert AttachedClustersClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AttachedClustersClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AttachedClustersClient._get_universe_domain(None, None) == AttachedClustersClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AttachedClustersClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AttachedClustersClient, "grpc"), + (AttachedClustersAsyncClient, "grpc_asyncio"), + (AttachedClustersClient, "rest"), +]) +def test_attached_clusters_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 == ( + 'gkemulticloud.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://gkemulticloud.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AttachedClustersGrpcTransport, "grpc"), + (transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AttachedClustersRestTransport, "rest"), +]) +def test_attached_clusters_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", [ + (AttachedClustersClient, "grpc"), + (AttachedClustersAsyncClient, "grpc_asyncio"), + (AttachedClustersClient, "rest"), +]) +def test_attached_clusters_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 == ( + 'gkemulticloud.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://gkemulticloud.googleapis.com' + ) + + +def test_attached_clusters_client_get_transport_class(): + transport = AttachedClustersClient.get_transport_class() + available_transports = [ + transports.AttachedClustersGrpcTransport, + transports.AttachedClustersRestTransport, + ] + assert transport in available_transports + + transport = AttachedClustersClient.get_transport_class("grpc") + assert transport == transports.AttachedClustersGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc"), + (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio"), + (AttachedClustersClient, transports.AttachedClustersRestTransport, "rest"), +]) +@mock.patch.object(AttachedClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersClient)) +@mock.patch.object(AttachedClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersAsyncClient)) +def test_attached_clusters_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(AttachedClustersClient, '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(AttachedClustersClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc", "true"), + (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc", "false"), + (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AttachedClustersClient, transports.AttachedClustersRestTransport, "rest", "true"), + (AttachedClustersClient, transports.AttachedClustersRestTransport, "rest", "false"), +]) +@mock.patch.object(AttachedClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersClient)) +@mock.patch.object(AttachedClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_attached_clusters_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + AttachedClustersClient, AttachedClustersAsyncClient +]) +@mock.patch.object(AttachedClustersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AttachedClustersClient)) +@mock.patch.object(AttachedClustersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AttachedClustersAsyncClient)) +def test_attached_clusters_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + AttachedClustersClient, AttachedClustersAsyncClient +]) +@mock.patch.object(AttachedClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersClient)) +@mock.patch.object(AttachedClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersAsyncClient)) +def test_attached_clusters_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AttachedClustersClient._DEFAULT_UNIVERSE + default_endpoint = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc"), + (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio"), + (AttachedClustersClient, transports.AttachedClustersRestTransport, "rest"), +]) +def test_attached_clusters_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc", grpc_helpers), + (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AttachedClustersClient, transports.AttachedClustersRestTransport, "rest", None), +]) +def test_attached_clusters_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_attached_clusters_client_client_options_from_dict(): + with mock.patch('google.cloud.gke_multicloud_v1.services.attached_clusters.transports.AttachedClustersGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AttachedClustersClient( + 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", [ + (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc", grpc_helpers), + (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_attached_clusters_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "gkemulticloud.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="gkemulticloud.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + attached_service.CreateAttachedClusterRequest, + dict, +]) +def test_create_attached_cluster(request_type, transport: str = 'grpc'): + client = AttachedClustersClient( + 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_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attached_service.CreateAttachedClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_attached_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attached_service.CreateAttachedClusterRequest( + parent='parent_value', + attached_cluster_id='attached_cluster_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_attached_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_attached_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attached_service.CreateAttachedClusterRequest( + parent='parent_value', + attached_cluster_id='attached_cluster_id_value', + ) + +def test_create_attached_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_attached_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_attached_cluster] = mock_rpc + request = {} + client.create_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_attached_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_attached_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_attached_cluster] = mock_rpc + + request = {} + await client.create_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_attached_cluster_async(transport: str = 'grpc_asyncio', request_type=attached_service.CreateAttachedClusterRequest): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_attached_cluster), + '__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_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attached_service.CreateAttachedClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_attached_cluster_async_from_dict(): + await test_create_attached_cluster_async(request_type=dict) + +def test_create_attached_cluster_field_headers(): + client = AttachedClustersClient( + 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 = attached_service.CreateAttachedClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_attached_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_attached_cluster(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_attached_cluster_field_headers_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = attached_service.CreateAttachedClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_attached_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_attached_cluster(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_attached_cluster_flattened(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_attached_cluster), + '__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_attached_cluster( + parent='parent_value', + attached_cluster=attached_resources.AttachedCluster(name='name_value'), + attached_cluster_id='attached_cluster_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].attached_cluster + mock_val = attached_resources.AttachedCluster(name='name_value') + assert arg == mock_val + arg = args[0].attached_cluster_id + mock_val = 'attached_cluster_id_value' + assert arg == mock_val + + +def test_create_attached_cluster_flattened_error(): + client = AttachedClustersClient( + 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_attached_cluster( + attached_service.CreateAttachedClusterRequest(), + parent='parent_value', + attached_cluster=attached_resources.AttachedCluster(name='name_value'), + attached_cluster_id='attached_cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_attached_cluster_flattened_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_attached_cluster), + '__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_attached_cluster( + parent='parent_value', + attached_cluster=attached_resources.AttachedCluster(name='name_value'), + attached_cluster_id='attached_cluster_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].attached_cluster + mock_val = attached_resources.AttachedCluster(name='name_value') + assert arg == mock_val + arg = args[0].attached_cluster_id + mock_val = 'attached_cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_attached_cluster_flattened_error_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_attached_cluster( + attached_service.CreateAttachedClusterRequest(), + parent='parent_value', + attached_cluster=attached_resources.AttachedCluster(name='name_value'), + attached_cluster_id='attached_cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + attached_service.UpdateAttachedClusterRequest, + dict, +]) +def test_update_attached_cluster(request_type, transport: str = 'grpc'): + client = AttachedClustersClient( + 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_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attached_service.UpdateAttachedClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_attached_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attached_service.UpdateAttachedClusterRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attached_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_attached_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attached_service.UpdateAttachedClusterRequest( + ) + +def test_update_attached_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_attached_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_attached_cluster] = mock_rpc + request = {} + client.update_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_attached_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_attached_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_attached_cluster] = mock_rpc + + request = {} + await client.update_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_attached_cluster_async(transport: str = 'grpc_asyncio', request_type=attached_service.UpdateAttachedClusterRequest): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_attached_cluster), + '__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_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attached_service.UpdateAttachedClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_attached_cluster_async_from_dict(): + await test_update_attached_cluster_async(request_type=dict) + +def test_update_attached_cluster_field_headers(): + client = AttachedClustersClient( + 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 = attached_service.UpdateAttachedClusterRequest() + + request.attached_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attached_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_attached_cluster(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', + 'attached_cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_attached_cluster_field_headers_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = attached_service.UpdateAttachedClusterRequest() + + request.attached_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attached_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_attached_cluster(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', + 'attached_cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_attached_cluster_flattened(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attached_cluster), + '__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_attached_cluster( + attached_cluster=attached_resources.AttachedCluster(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].attached_cluster + mock_val = attached_resources.AttachedCluster(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_attached_cluster_flattened_error(): + client = AttachedClustersClient( + 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_attached_cluster( + attached_service.UpdateAttachedClusterRequest(), + attached_cluster=attached_resources.AttachedCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_attached_cluster_flattened_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attached_cluster), + '__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_attached_cluster( + attached_cluster=attached_resources.AttachedCluster(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].attached_cluster + mock_val = attached_resources.AttachedCluster(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_attached_cluster_flattened_error_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_attached_cluster( + attached_service.UpdateAttachedClusterRequest(), + attached_cluster=attached_resources.AttachedCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + attached_service.ImportAttachedClusterRequest, + dict, +]) +def test_import_attached_cluster(request_type, transport: str = 'grpc'): + client = AttachedClustersClient( + 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.import_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attached_service.ImportAttachedClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_attached_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attached_service.ImportAttachedClusterRequest( + parent='parent_value', + fleet_membership='fleet_membership_value', + platform_version='platform_version_value', + distribution='distribution_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_attached_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.import_attached_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attached_service.ImportAttachedClusterRequest( + parent='parent_value', + fleet_membership='fleet_membership_value', + platform_version='platform_version_value', + distribution='distribution_value', + ) + +def test_import_attached_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_attached_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_attached_cluster] = mock_rpc + request = {} + client.import_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_import_attached_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.import_attached_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.import_attached_cluster] = mock_rpc + + request = {} + await client.import_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.import_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_import_attached_cluster_async(transport: str = 'grpc_asyncio', request_type=attached_service.ImportAttachedClusterRequest): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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.import_attached_cluster), + '__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.import_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attached_service.ImportAttachedClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_attached_cluster_async_from_dict(): + await test_import_attached_cluster_async(request_type=dict) + +def test_import_attached_cluster_field_headers(): + client = AttachedClustersClient( + 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 = attached_service.ImportAttachedClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_attached_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_attached_cluster(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_import_attached_cluster_field_headers_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = attached_service.ImportAttachedClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_attached_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_attached_cluster(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_import_attached_cluster_flattened(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_attached_cluster), + '__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.import_attached_cluster( + parent='parent_value', + fleet_membership='fleet_membership_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].fleet_membership + mock_val = 'fleet_membership_value' + assert arg == mock_val + + +def test_import_attached_cluster_flattened_error(): + client = AttachedClustersClient( + 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.import_attached_cluster( + attached_service.ImportAttachedClusterRequest(), + parent='parent_value', + fleet_membership='fleet_membership_value', + ) + +@pytest.mark.asyncio +async def test_import_attached_cluster_flattened_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_attached_cluster), + '__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.import_attached_cluster( + parent='parent_value', + fleet_membership='fleet_membership_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].fleet_membership + mock_val = 'fleet_membership_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_import_attached_cluster_flattened_error_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_attached_cluster( + attached_service.ImportAttachedClusterRequest(), + parent='parent_value', + fleet_membership='fleet_membership_value', + ) + + +@pytest.mark.parametrize("request_type", [ + attached_service.GetAttachedClusterRequest, + dict, +]) +def test_get_attached_cluster(request_type, transport: str = 'grpc'): + client = AttachedClustersClient( + 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_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_resources.AttachedCluster( + name='name_value', + description='description_value', + platform_version='platform_version_value', + distribution='distribution_value', + cluster_region='cluster_region_value', + state=attached_resources.AttachedCluster.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + kubernetes_version='kubernetes_version_value', + ) + response = client.get_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attached_service.GetAttachedClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_resources.AttachedCluster) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.platform_version == 'platform_version_value' + assert response.distribution == 'distribution_value' + assert response.cluster_region == 'cluster_region_value' + assert response.state == attached_resources.AttachedCluster.State.PROVISIONING + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.kubernetes_version == 'kubernetes_version_value' + + +def test_get_attached_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attached_service.GetAttachedClusterRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_attached_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attached_service.GetAttachedClusterRequest( + name='name_value', + ) + +def test_get_attached_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_attached_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_attached_cluster] = mock_rpc + request = {} + client.get_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_attached_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_attached_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_attached_cluster] = mock_rpc + + request = {} + await client.get_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_attached_cluster_async(transport: str = 'grpc_asyncio', request_type=attached_service.GetAttachedClusterRequest): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedCluster( + name='name_value', + description='description_value', + platform_version='platform_version_value', + distribution='distribution_value', + cluster_region='cluster_region_value', + state=attached_resources.AttachedCluster.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + kubernetes_version='kubernetes_version_value', + )) + response = await client.get_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attached_service.GetAttachedClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_resources.AttachedCluster) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.platform_version == 'platform_version_value' + assert response.distribution == 'distribution_value' + assert response.cluster_region == 'cluster_region_value' + assert response.state == attached_resources.AttachedCluster.State.PROVISIONING + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.kubernetes_version == 'kubernetes_version_value' + + +@pytest.mark.asyncio +async def test_get_attached_cluster_async_from_dict(): + await test_get_attached_cluster_async(request_type=dict) + +def test_get_attached_cluster_field_headers(): + client = AttachedClustersClient( + 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 = attached_service.GetAttachedClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_cluster), + '__call__') as call: + call.return_value = attached_resources.AttachedCluster() + client.get_attached_cluster(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_attached_cluster_field_headers_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = attached_service.GetAttachedClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedCluster()) + await client.get_attached_cluster(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_attached_cluster_flattened(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_resources.AttachedCluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attached_cluster( + 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_attached_cluster_flattened_error(): + client = AttachedClustersClient( + 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_attached_cluster( + attached_service.GetAttachedClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attached_cluster_flattened_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_resources.AttachedCluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedCluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attached_cluster( + 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_attached_cluster_flattened_error_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_attached_cluster( + attached_service.GetAttachedClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + attached_service.ListAttachedClustersRequest, + dict, +]) +def test_list_attached_clusters(request_type, transport: str = 'grpc'): + client = AttachedClustersClient( + 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_attached_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_service.ListAttachedClustersResponse( + next_page_token='next_page_token_value', + ) + response = client.list_attached_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attached_service.ListAttachedClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttachedClustersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_attached_clusters_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attached_service.ListAttachedClustersRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attached_clusters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_attached_clusters(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attached_service.ListAttachedClustersRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_attached_clusters_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_attached_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_attached_clusters] = mock_rpc + request = {} + client.list_attached_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_attached_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_attached_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_attached_clusters in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_attached_clusters] = mock_rpc + + request = {} + await client.list_attached_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_attached_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_attached_clusters_async(transport: str = 'grpc_asyncio', request_type=attached_service.ListAttachedClustersRequest): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_attached_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attached_service.ListAttachedClustersResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_attached_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attached_service.ListAttachedClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttachedClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_attached_clusters_async_from_dict(): + await test_list_attached_clusters_async(request_type=dict) + +def test_list_attached_clusters_field_headers(): + client = AttachedClustersClient( + 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 = attached_service.ListAttachedClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attached_clusters), + '__call__') as call: + call.return_value = attached_service.ListAttachedClustersResponse() + client.list_attached_clusters(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_attached_clusters_field_headers_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = attached_service.ListAttachedClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attached_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.ListAttachedClustersResponse()) + await client.list_attached_clusters(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_attached_clusters_flattened(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attached_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_service.ListAttachedClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_attached_clusters( + 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_attached_clusters_flattened_error(): + client = AttachedClustersClient( + 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_attached_clusters( + attached_service.ListAttachedClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_attached_clusters_flattened_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attached_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_service.ListAttachedClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.ListAttachedClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_attached_clusters( + 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_attached_clusters_flattened_error_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_attached_clusters( + attached_service.ListAttachedClustersRequest(), + parent='parent_value', + ) + + +def test_list_attached_clusters_pager(transport_name: str = "grpc"): + client = AttachedClustersClient( + 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_attached_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + ], + next_page_token='abc', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[], + next_page_token='def', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + ], + next_page_token='ghi', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_attached_clusters(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, attached_resources.AttachedCluster) + for i in results) +def test_list_attached_clusters_pages(transport_name: str = "grpc"): + client = AttachedClustersClient( + 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_attached_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + ], + next_page_token='abc', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[], + next_page_token='def', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + ], + next_page_token='ghi', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_attached_clusters(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_attached_clusters_async_pager(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attached_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + ], + next_page_token='abc', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[], + next_page_token='def', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + ], + next_page_token='ghi', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_attached_clusters(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, attached_resources.AttachedCluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_attached_clusters_async_pages(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attached_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + ], + next_page_token='abc', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[], + next_page_token='def', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + ], + next_page_token='ghi', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + ], + ), + 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_attached_clusters(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", [ + attached_service.DeleteAttachedClusterRequest, + dict, +]) +def test_delete_attached_cluster(request_type, transport: str = 'grpc'): + client = AttachedClustersClient( + 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_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attached_service.DeleteAttachedClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_attached_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attached_service.DeleteAttachedClusterRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_attached_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_attached_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attached_service.DeleteAttachedClusterRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_attached_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_attached_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_attached_cluster] = mock_rpc + request = {} + client.delete_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_attached_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_attached_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_attached_cluster] = mock_rpc + + request = {} + await client.delete_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_attached_cluster_async(transport: str = 'grpc_asyncio', request_type=attached_service.DeleteAttachedClusterRequest): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_attached_cluster), + '__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_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attached_service.DeleteAttachedClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_attached_cluster_async_from_dict(): + await test_delete_attached_cluster_async(request_type=dict) + +def test_delete_attached_cluster_field_headers(): + client = AttachedClustersClient( + 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 = attached_service.DeleteAttachedClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_attached_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_attached_cluster(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_attached_cluster_field_headers_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = attached_service.DeleteAttachedClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_attached_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_attached_cluster(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_attached_cluster_flattened(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_attached_cluster), + '__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_attached_cluster( + 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_attached_cluster_flattened_error(): + client = AttachedClustersClient( + 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_attached_cluster( + attached_service.DeleteAttachedClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_attached_cluster_flattened_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_attached_cluster), + '__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_attached_cluster( + 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_attached_cluster_flattened_error_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_attached_cluster( + attached_service.DeleteAttachedClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + attached_service.GetAttachedServerConfigRequest, + dict, +]) +def test_get_attached_server_config(request_type, transport: str = 'grpc'): + client = AttachedClustersClient( + 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_attached_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_resources.AttachedServerConfig( + name='name_value', + ) + response = client.get_attached_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attached_service.GetAttachedServerConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_resources.AttachedServerConfig) + assert response.name == 'name_value' + + +def test_get_attached_server_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attached_service.GetAttachedServerConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_server_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_attached_server_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attached_service.GetAttachedServerConfigRequest( + name='name_value', + ) + +def test_get_attached_server_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_attached_server_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_attached_server_config] = mock_rpc + request = {} + client.get_attached_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_attached_server_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_attached_server_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_attached_server_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_attached_server_config] = mock_rpc + + request = {} + await client.get_attached_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_attached_server_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_attached_server_config_async(transport: str = 'grpc_asyncio', request_type=attached_service.GetAttachedServerConfigRequest): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_attached_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedServerConfig( + name='name_value', + )) + response = await client.get_attached_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attached_service.GetAttachedServerConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_resources.AttachedServerConfig) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_attached_server_config_async_from_dict(): + await test_get_attached_server_config_async(request_type=dict) + +def test_get_attached_server_config_field_headers(): + client = AttachedClustersClient( + 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 = attached_service.GetAttachedServerConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_server_config), + '__call__') as call: + call.return_value = attached_resources.AttachedServerConfig() + client.get_attached_server_config(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_attached_server_config_field_headers_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = attached_service.GetAttachedServerConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_server_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedServerConfig()) + await client.get_attached_server_config(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_attached_server_config_flattened(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_resources.AttachedServerConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attached_server_config( + 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_attached_server_config_flattened_error(): + client = AttachedClustersClient( + 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_attached_server_config( + attached_service.GetAttachedServerConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attached_server_config_flattened_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_resources.AttachedServerConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedServerConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attached_server_config( + 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_attached_server_config_flattened_error_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_attached_server_config( + attached_service.GetAttachedServerConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + attached_service.GenerateAttachedClusterInstallManifestRequest, + dict, +]) +def test_generate_attached_cluster_install_manifest(request_type, transport: str = 'grpc'): + client = AttachedClustersClient( + 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_attached_cluster_install_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse( + manifest='manifest_value', + ) + response = client.generate_attached_cluster_install_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attached_service.GenerateAttachedClusterInstallManifestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_service.GenerateAttachedClusterInstallManifestResponse) + assert response.manifest == 'manifest_value' + + +def test_generate_attached_cluster_install_manifest_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attached_service.GenerateAttachedClusterInstallManifestRequest( + parent='parent_value', + attached_cluster_id='attached_cluster_id_value', + platform_version='platform_version_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_install_manifest), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_attached_cluster_install_manifest(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attached_service.GenerateAttachedClusterInstallManifestRequest( + parent='parent_value', + attached_cluster_id='attached_cluster_id_value', + platform_version='platform_version_value', + ) + +def test_generate_attached_cluster_install_manifest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_attached_cluster_install_manifest in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_attached_cluster_install_manifest] = mock_rpc + request = {} + client.generate_attached_cluster_install_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_attached_cluster_install_manifest(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_attached_cluster_install_manifest_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_attached_cluster_install_manifest in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.generate_attached_cluster_install_manifest] = mock_rpc + + request = {} + await client.generate_attached_cluster_install_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_attached_cluster_install_manifest(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_attached_cluster_install_manifest_async(transport: str = 'grpc_asyncio', request_type=attached_service.GenerateAttachedClusterInstallManifestRequest): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_attached_cluster_install_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterInstallManifestResponse( + manifest='manifest_value', + )) + response = await client.generate_attached_cluster_install_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attached_service.GenerateAttachedClusterInstallManifestRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_service.GenerateAttachedClusterInstallManifestResponse) + assert response.manifest == 'manifest_value' + + +@pytest.mark.asyncio +async def test_generate_attached_cluster_install_manifest_async_from_dict(): + await test_generate_attached_cluster_install_manifest_async(request_type=dict) + +def test_generate_attached_cluster_install_manifest_field_headers(): + client = AttachedClustersClient( + 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 = attached_service.GenerateAttachedClusterInstallManifestRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_install_manifest), + '__call__') as call: + call.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() + client.generate_attached_cluster_install_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_attached_cluster_install_manifest_field_headers_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = attached_service.GenerateAttachedClusterInstallManifestRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_install_manifest), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterInstallManifestResponse()) + await client.generate_attached_cluster_install_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_generate_attached_cluster_install_manifest_flattened(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_install_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_attached_cluster_install_manifest( + parent='parent_value', + attached_cluster_id='attached_cluster_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].attached_cluster_id + mock_val = 'attached_cluster_id_value' + assert arg == mock_val + + +def test_generate_attached_cluster_install_manifest_flattened_error(): + client = AttachedClustersClient( + 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.generate_attached_cluster_install_manifest( + attached_service.GenerateAttachedClusterInstallManifestRequest(), + parent='parent_value', + attached_cluster_id='attached_cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_generate_attached_cluster_install_manifest_flattened_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_install_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterInstallManifestResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_attached_cluster_install_manifest( + parent='parent_value', + attached_cluster_id='attached_cluster_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].attached_cluster_id + mock_val = 'attached_cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_generate_attached_cluster_install_manifest_flattened_error_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.generate_attached_cluster_install_manifest( + attached_service.GenerateAttachedClusterInstallManifestRequest(), + parent='parent_value', + attached_cluster_id='attached_cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + attached_service.GenerateAttachedClusterAgentTokenRequest, + dict, +]) +def test_generate_attached_cluster_agent_token(request_type, transport: str = 'grpc'): + client = AttachedClustersClient( + 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_attached_cluster_agent_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attached_service.GenerateAttachedClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + ) + response = client.generate_attached_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attached_service.GenerateAttachedClusterAgentTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_service.GenerateAttachedClusterAgentTokenResponse) + assert response.access_token == 'access_token_value' + assert response.expires_in == 1078 + assert response.token_type == 'token_type_value' + + +def test_generate_attached_cluster_agent_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attached_service.GenerateAttachedClusterAgentTokenRequest( + attached_cluster='attached_cluster_value', + subject_token='subject_token_value', + subject_token_type='subject_token_type_value', + version='version_value', + grant_type='grant_type_value', + audience='audience_value', + scope='scope_value', + requested_token_type='requested_token_type_value', + options='options_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_agent_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_attached_cluster_agent_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attached_service.GenerateAttachedClusterAgentTokenRequest( + attached_cluster='attached_cluster_value', + subject_token='subject_token_value', + subject_token_type='subject_token_type_value', + version='version_value', + grant_type='grant_type_value', + audience='audience_value', + scope='scope_value', + requested_token_type='requested_token_type_value', + options='options_value', + ) + +def test_generate_attached_cluster_agent_token_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_attached_cluster_agent_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_attached_cluster_agent_token] = mock_rpc + request = {} + client.generate_attached_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_attached_cluster_agent_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_attached_cluster_agent_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_attached_cluster_agent_token in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.generate_attached_cluster_agent_token] = mock_rpc + + request = {} + await client.generate_attached_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_attached_cluster_agent_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_attached_cluster_agent_token_async(transport: str = 'grpc_asyncio', request_type=attached_service.GenerateAttachedClusterAgentTokenRequest): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_attached_cluster_agent_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + )) + response = await client.generate_attached_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attached_service.GenerateAttachedClusterAgentTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_service.GenerateAttachedClusterAgentTokenResponse) + assert response.access_token == 'access_token_value' + assert response.expires_in == 1078 + assert response.token_type == 'token_type_value' + + +@pytest.mark.asyncio +async def test_generate_attached_cluster_agent_token_async_from_dict(): + await test_generate_attached_cluster_agent_token_async(request_type=dict) + +def test_generate_attached_cluster_agent_token_field_headers(): + client = AttachedClustersClient( + 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 = attached_service.GenerateAttachedClusterAgentTokenRequest() + + request.attached_cluster = 'attached_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_agent_token), + '__call__') as call: + call.return_value = attached_service.GenerateAttachedClusterAgentTokenResponse() + client.generate_attached_cluster_agent_token(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', + 'attached_cluster=attached_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_attached_cluster_agent_token_field_headers_async(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = attached_service.GenerateAttachedClusterAgentTokenRequest() + + request.attached_cluster = 'attached_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_agent_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterAgentTokenResponse()) + await client.generate_attached_cluster_agent_token(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', + 'attached_cluster=attached_cluster_value', + ) in kw['metadata'] + + +def test_create_attached_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_attached_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_attached_cluster] = mock_rpc + + request = {} + client.create_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_attached_cluster_rest_required_fields(request_type=attached_service.CreateAttachedClusterRequest): + transport_class = transports.AttachedClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["attached_cluster_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "attachedClusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_attached_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "attachedClusterId" in jsonified_request + assert jsonified_request["attachedClusterId"] == request_init["attached_cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["attachedClusterId"] = 'attached_cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_attached_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("attached_cluster_id", "validate_only", )) + 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 "attachedClusterId" in jsonified_request + assert jsonified_request["attachedClusterId"] == 'attached_cluster_id_value' + + client = AttachedClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_attached_cluster(request) + + expected_params = [ + ( + "attachedClusterId", + "", + ), + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_attached_cluster_rest_unset_required_fields(): + transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_attached_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("attachedClusterId", "validateOnly", )) & set(("parent", "attachedCluster", "attachedClusterId", ))) + + +def test_create_attached_cluster_rest_flattened(): + client = AttachedClustersClient( + 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', + attached_cluster=attached_resources.AttachedCluster(name='name_value'), + attached_cluster_id='attached_cluster_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_attached_cluster(**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/*}/attachedClusters" % client.transport._host, args[1]) + + +def test_create_attached_cluster_rest_flattened_error(transport: str = 'rest'): + client = AttachedClustersClient( + 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_attached_cluster( + attached_service.CreateAttachedClusterRequest(), + parent='parent_value', + attached_cluster=attached_resources.AttachedCluster(name='name_value'), + attached_cluster_id='attached_cluster_id_value', + ) + + +def test_update_attached_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_attached_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_attached_cluster] = mock_rpc + + request = {} + client.update_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_attached_cluster_rest_required_fields(request_type=attached_service.UpdateAttachedClusterRequest): + transport_class = transports.AttachedClustersRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_attached_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_attached_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AttachedClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_attached_cluster(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_attached_cluster_rest_unset_required_fields(): + transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_attached_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("attachedCluster", "updateMask", ))) + + +def test_update_attached_cluster_rest_flattened(): + client = AttachedClustersClient( + 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 = {'attached_cluster': {'name': 'projects/sample1/locations/sample2/attachedClusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + attached_cluster=attached_resources.AttachedCluster(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_attached_cluster(**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/{attached_cluster.name=projects/*/locations/*/attachedClusters/*}" % client.transport._host, args[1]) + + +def test_update_attached_cluster_rest_flattened_error(transport: str = 'rest'): + client = AttachedClustersClient( + 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_attached_cluster( + attached_service.UpdateAttachedClusterRequest(), + attached_cluster=attached_resources.AttachedCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_import_attached_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_attached_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_attached_cluster] = mock_rpc + + request = {} + client.import_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_import_attached_cluster_rest_required_fields(request_type=attached_service.ImportAttachedClusterRequest): + transport_class = transports.AttachedClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["fleet_membership"] = "" + request_init["platform_version"] = "" + request_init["distribution"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_attached_cluster._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' + jsonified_request["fleetMembership"] = 'fleet_membership_value' + jsonified_request["platformVersion"] = 'platform_version_value' + jsonified_request["distribution"] = 'distribution_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_attached_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "fleetMembership" in jsonified_request + assert jsonified_request["fleetMembership"] == 'fleet_membership_value' + assert "platformVersion" in jsonified_request + assert jsonified_request["platformVersion"] == 'platform_version_value' + assert "distribution" in jsonified_request + assert jsonified_request["distribution"] == 'distribution_value' + + client = AttachedClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.import_attached_cluster(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_attached_cluster_rest_unset_required_fields(): + transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_attached_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "fleetMembership", "platformVersion", "distribution", ))) + + +def test_import_attached_cluster_rest_flattened(): + client = AttachedClustersClient( + 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', + fleet_membership='fleet_membership_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.import_attached_cluster(**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/*}/attachedClusters:import" % client.transport._host, args[1]) + + +def test_import_attached_cluster_rest_flattened_error(transport: str = 'rest'): + client = AttachedClustersClient( + 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.import_attached_cluster( + attached_service.ImportAttachedClusterRequest(), + parent='parent_value', + fleet_membership='fleet_membership_value', + ) + + +def test_get_attached_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_attached_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_attached_cluster] = mock_rpc + + request = {} + client.get_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_attached_cluster_rest_required_fields(request_type=attached_service.GetAttachedClusterRequest): + transport_class = transports.AttachedClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_attached_cluster._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_attached_cluster._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 = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = attached_resources.AttachedCluster() + # 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 = attached_resources.AttachedCluster.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_attached_cluster(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_attached_cluster_rest_unset_required_fields(): + transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_attached_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_attached_cluster_rest_flattened(): + client = AttachedClustersClient( + 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 = attached_resources.AttachedCluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = attached_resources.AttachedCluster.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_attached_cluster(**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/*/attachedClusters/*}" % client.transport._host, args[1]) + + +def test_get_attached_cluster_rest_flattened_error(transport: str = 'rest'): + client = AttachedClustersClient( + 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_attached_cluster( + attached_service.GetAttachedClusterRequest(), + name='name_value', + ) + + +def test_list_attached_clusters_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_attached_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_attached_clusters] = mock_rpc + + request = {} + client.list_attached_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_attached_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_attached_clusters_rest_required_fields(request_type=attached_service.ListAttachedClustersRequest): + transport_class = transports.AttachedClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_attached_clusters._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_attached_clusters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + 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 = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = attached_service.ListAttachedClustersResponse() + # 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 = attached_service.ListAttachedClustersResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_attached_clusters(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_attached_clusters_rest_unset_required_fields(): + transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_attached_clusters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_attached_clusters_rest_flattened(): + client = AttachedClustersClient( + 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 = attached_service.ListAttachedClustersResponse() + + # 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 = attached_service.ListAttachedClustersResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_attached_clusters(**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/*}/attachedClusters" % client.transport._host, args[1]) + + +def test_list_attached_clusters_rest_flattened_error(transport: str = 'rest'): + client = AttachedClustersClient( + 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_attached_clusters( + attached_service.ListAttachedClustersRequest(), + parent='parent_value', + ) + + +def test_list_attached_clusters_rest_pager(transport: str = 'rest'): + client = AttachedClustersClient( + 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 = ( + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + ], + next_page_token='abc', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[], + next_page_token='def', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + ], + next_page_token='ghi', + ), + attached_service.ListAttachedClustersResponse( + attached_clusters=[ + attached_resources.AttachedCluster(), + attached_resources.AttachedCluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(attached_service.ListAttachedClustersResponse.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_attached_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, attached_resources.AttachedCluster) + for i in results) + + pages = list(client.list_attached_clusters(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_attached_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_attached_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_attached_cluster] = mock_rpc + + request = {} + client.delete_attached_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_attached_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_attached_cluster_rest_required_fields(request_type=attached_service.DeleteAttachedClusterRequest): + transport_class = transports.AttachedClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_attached_cluster._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_attached_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "etag", "ignore_errors", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AttachedClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_attached_cluster(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_attached_cluster_rest_unset_required_fields(): + transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_attached_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "etag", "ignoreErrors", "validateOnly", )) & set(("name", ))) + + +def test_delete_attached_cluster_rest_flattened(): + client = AttachedClustersClient( + 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/attachedClusters/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_attached_cluster(**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/*/attachedClusters/*}" % client.transport._host, args[1]) + + +def test_delete_attached_cluster_rest_flattened_error(transport: str = 'rest'): + client = AttachedClustersClient( + 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_attached_cluster( + attached_service.DeleteAttachedClusterRequest(), + name='name_value', + ) + + +def test_get_attached_server_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_attached_server_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_attached_server_config] = mock_rpc + + request = {} + client.get_attached_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_attached_server_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_attached_server_config_rest_required_fields(request_type=attached_service.GetAttachedServerConfigRequest): + transport_class = transports.AttachedClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_attached_server_config._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_attached_server_config._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 = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = attached_resources.AttachedServerConfig() + # 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 = attached_resources.AttachedServerConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_attached_server_config(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_attached_server_config_rest_unset_required_fields(): + transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_attached_server_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_attached_server_config_rest_flattened(): + client = AttachedClustersClient( + 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 = attached_resources.AttachedServerConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/attachedServerConfig'} + + # 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 = attached_resources.AttachedServerConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_attached_server_config(**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/*/attachedServerConfig}" % client.transport._host, args[1]) + + +def test_get_attached_server_config_rest_flattened_error(transport: str = 'rest'): + client = AttachedClustersClient( + 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_attached_server_config( + attached_service.GetAttachedServerConfigRequest(), + name='name_value', + ) + + +def test_generate_attached_cluster_install_manifest_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_attached_cluster_install_manifest in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_attached_cluster_install_manifest] = mock_rpc + + request = {} + client.generate_attached_cluster_install_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_attached_cluster_install_manifest(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_attached_cluster_install_manifest_rest_required_fields(request_type=attached_service.GenerateAttachedClusterInstallManifestRequest): + transport_class = transports.AttachedClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["attached_cluster_id"] = "" + request_init["platform_version"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "attachedClusterId" not in jsonified_request + assert "platformVersion" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_attached_cluster_install_manifest._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "attachedClusterId" in jsonified_request + assert jsonified_request["attachedClusterId"] == request_init["attached_cluster_id"] + assert "platformVersion" in jsonified_request + assert jsonified_request["platformVersion"] == request_init["platform_version"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["attachedClusterId"] = 'attached_cluster_id_value' + jsonified_request["platformVersion"] = 'platform_version_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_attached_cluster_install_manifest._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("attached_cluster_id", "platform_version", "proxy_config", )) + 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 "attachedClusterId" in jsonified_request + assert jsonified_request["attachedClusterId"] == 'attached_cluster_id_value' + assert "platformVersion" in jsonified_request + assert jsonified_request["platformVersion"] == 'platform_version_value' + + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() + # 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 = attached_service.GenerateAttachedClusterInstallManifestResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_attached_cluster_install_manifest(request) + + expected_params = [ + ( + "attachedClusterId", + "", + ), + ( + "platformVersion", + "", + ), + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_attached_cluster_install_manifest_rest_unset_required_fields(): + transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_attached_cluster_install_manifest._get_unset_required_fields({}) + assert set(unset_fields) == (set(("attachedClusterId", "platformVersion", "proxyConfig", )) & set(("parent", "attachedClusterId", "platformVersion", ))) + + +def test_generate_attached_cluster_install_manifest_rest_flattened(): + client = AttachedClustersClient( + 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 = attached_service.GenerateAttachedClusterInstallManifestResponse() + + # 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', + attached_cluster_id='attached_cluster_id_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 = attached_service.GenerateAttachedClusterInstallManifestResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.generate_attached_cluster_install_manifest(**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/*}:generateAttachedClusterInstallManifest" % client.transport._host, args[1]) + + +def test_generate_attached_cluster_install_manifest_rest_flattened_error(transport: str = 'rest'): + client = AttachedClustersClient( + 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.generate_attached_cluster_install_manifest( + attached_service.GenerateAttachedClusterInstallManifestRequest(), + parent='parent_value', + attached_cluster_id='attached_cluster_id_value', + ) + + +def test_generate_attached_cluster_agent_token_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_attached_cluster_agent_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_attached_cluster_agent_token] = mock_rpc + + request = {} + client.generate_attached_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_attached_cluster_agent_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_attached_cluster_agent_token_rest_required_fields(request_type=attached_service.GenerateAttachedClusterAgentTokenRequest): + transport_class = transports.AttachedClustersRestTransport + + request_init = {} + request_init["attached_cluster"] = "" + request_init["subject_token"] = "" + request_init["subject_token_type"] = "" + request_init["version"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_attached_cluster_agent_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["attachedCluster"] = 'attached_cluster_value' + jsonified_request["subjectToken"] = 'subject_token_value' + jsonified_request["subjectTokenType"] = 'subject_token_type_value' + jsonified_request["version"] = 'version_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_attached_cluster_agent_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "attachedCluster" in jsonified_request + assert jsonified_request["attachedCluster"] == 'attached_cluster_value' + assert "subjectToken" in jsonified_request + assert jsonified_request["subjectToken"] == 'subject_token_value' + assert "subjectTokenType" in jsonified_request + assert jsonified_request["subjectTokenType"] == 'subject_token_type_value' + assert "version" in jsonified_request + assert jsonified_request["version"] == 'version_value' + + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = attached_service.GenerateAttachedClusterAgentTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = attached_service.GenerateAttachedClusterAgentTokenResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_attached_cluster_agent_token(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_attached_cluster_agent_token_rest_unset_required_fields(): + transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_attached_cluster_agent_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("attachedCluster", "subjectToken", "subjectTokenType", "version", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AttachedClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AttachedClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AttachedClustersClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AttachedClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AttachedClustersClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AttachedClustersClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AttachedClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AttachedClustersClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AttachedClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AttachedClustersClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AttachedClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AttachedClustersGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AttachedClustersGrpcTransport, + transports.AttachedClustersGrpcAsyncIOTransport, + transports.AttachedClustersRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = AttachedClustersClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_attached_cluster_empty_call_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_attached_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.CreateAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_attached_cluster_empty_call_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attached_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.UpdateAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_attached_cluster_empty_call_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_attached_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.ImportAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_attached_cluster_empty_call_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_cluster), + '__call__') as call: + call.return_value = attached_resources.AttachedCluster() + client.get_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GetAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_attached_clusters_empty_call_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_attached_clusters), + '__call__') as call: + call.return_value = attached_service.ListAttachedClustersResponse() + client.list_attached_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.ListAttachedClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_attached_cluster_empty_call_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_attached_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.DeleteAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_attached_server_config_empty_call_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_server_config), + '__call__') as call: + call.return_value = attached_resources.AttachedServerConfig() + client.get_attached_server_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GetAttachedServerConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_attached_cluster_install_manifest_empty_call_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_install_manifest), + '__call__') as call: + call.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() + client.generate_attached_cluster_install_manifest(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GenerateAttachedClusterInstallManifestRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_attached_cluster_agent_token_empty_call_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_agent_token), + '__call__') as call: + call.return_value = attached_service.GenerateAttachedClusterAgentTokenResponse() + client.generate_attached_cluster_agent_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GenerateAttachedClusterAgentTokenRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AttachedClustersAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_attached_cluster_empty_call_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.CreateAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_attached_cluster_empty_call_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.UpdateAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_attached_cluster_empty_call_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.import_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.ImportAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_attached_cluster_empty_call_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedCluster( + name='name_value', + description='description_value', + platform_version='platform_version_value', + distribution='distribution_value', + cluster_region='cluster_region_value', + state=attached_resources.AttachedCluster.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + kubernetes_version='kubernetes_version_value', + )) + await client.get_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GetAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_attached_clusters_empty_call_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_attached_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.ListAttachedClustersResponse( + next_page_token='next_page_token_value', + )) + await client.list_attached_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.ListAttachedClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_attached_cluster_empty_call_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_attached_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.DeleteAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_attached_server_config_empty_call_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedServerConfig( + name='name_value', + )) + await client.get_attached_server_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GetAttachedServerConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_attached_cluster_install_manifest_empty_call_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_install_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterInstallManifestResponse( + manifest='manifest_value', + )) + await client.generate_attached_cluster_install_manifest(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GenerateAttachedClusterInstallManifestRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_attached_cluster_agent_token_empty_call_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_agent_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + )) + await client.generate_attached_cluster_agent_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GenerateAttachedClusterAgentTokenRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AttachedClustersClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_attached_cluster_rest_bad_request(request_type=attached_service.CreateAttachedClusterRequest): + client = AttachedClustersClient( + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_attached_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + attached_service.CreateAttachedClusterRequest, + dict, +]) +def test_create_attached_cluster_rest_call_success(request_type): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["attached_cluster"] = {'name': 'name_value', 'description': 'description_value', 'oidc_config': {'issuer_url': 'issuer_url_value', 'jwks': b'jwks_blob'}, 'platform_version': 'platform_version_value', 'distribution': 'distribution_value', 'cluster_region': 'cluster_region_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'kubernetes_version': 'kubernetes_version_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}, 'proxy_config': {'kubernetes_secret': {'name': 'name_value', 'namespace': 'namespace_value'}}, 'binary_authorization': {'evaluation_mode': 1}, 'security_posture_config': {'vulnerability_mode': 1}, 'tags': {}} + # 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 = attached_service.CreateAttachedClusterRequest.meta.fields["attached_cluster"] + + 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["attached_cluster"].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["attached_cluster"][field])): + del request_init["attached_cluster"][field][i][subfield] + else: + del request_init["attached_cluster"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_attached_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_attached_cluster_rest_interceptors(null_interceptor): + transport = transports.AttachedClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), + ) + client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_create_attached_cluster") as post, \ + mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_create_attached_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attached_service.CreateAttachedClusterRequest.pb(attached_service.CreateAttachedClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = attached_service.CreateAttachedClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_attached_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_attached_cluster_rest_bad_request(request_type=attached_service.UpdateAttachedClusterRequest): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'attached_cluster': {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_attached_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + attached_service.UpdateAttachedClusterRequest, + dict, +]) +def test_update_attached_cluster_rest_call_success(request_type): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'attached_cluster': {'name': 'projects/sample1/locations/sample2/attachedClusters/sample3'}} + request_init["attached_cluster"] = {'name': 'projects/sample1/locations/sample2/attachedClusters/sample3', 'description': 'description_value', 'oidc_config': {'issuer_url': 'issuer_url_value', 'jwks': b'jwks_blob'}, 'platform_version': 'platform_version_value', 'distribution': 'distribution_value', 'cluster_region': 'cluster_region_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'kubernetes_version': 'kubernetes_version_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}, 'proxy_config': {'kubernetes_secret': {'name': 'name_value', 'namespace': 'namespace_value'}}, 'binary_authorization': {'evaluation_mode': 1}, 'security_posture_config': {'vulnerability_mode': 1}, 'tags': {}} + # 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 = attached_service.UpdateAttachedClusterRequest.meta.fields["attached_cluster"] + + 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["attached_cluster"].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["attached_cluster"][field])): + del request_init["attached_cluster"][field][i][subfield] + else: + del request_init["attached_cluster"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_attached_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_attached_cluster_rest_interceptors(null_interceptor): + transport = transports.AttachedClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), + ) + client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_update_attached_cluster") as post, \ + mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_update_attached_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attached_service.UpdateAttachedClusterRequest.pb(attached_service.UpdateAttachedClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = attached_service.UpdateAttachedClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_attached_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_attached_cluster_rest_bad_request(request_type=attached_service.ImportAttachedClusterRequest): + client = AttachedClustersClient( + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.import_attached_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + attached_service.ImportAttachedClusterRequest, + dict, +]) +def test_import_attached_cluster_rest_call_success(request_type): + client = AttachedClustersClient( + 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 = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.import_attached_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_attached_cluster_rest_interceptors(null_interceptor): + transport = transports.AttachedClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), + ) + client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_import_attached_cluster") as post, \ + mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_import_attached_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attached_service.ImportAttachedClusterRequest.pb(attached_service.ImportAttachedClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = attached_service.ImportAttachedClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_attached_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_attached_cluster_rest_bad_request(request_type=attached_service.GetAttachedClusterRequest): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_attached_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + attached_service.GetAttachedClusterRequest, + dict, +]) +def test_get_attached_cluster_rest_call_success(request_type): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = attached_resources.AttachedCluster( + name='name_value', + description='description_value', + platform_version='platform_version_value', + distribution='distribution_value', + cluster_region='cluster_region_value', + state=attached_resources.AttachedCluster.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + kubernetes_version='kubernetes_version_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = attached_resources.AttachedCluster.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_attached_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_resources.AttachedCluster) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.platform_version == 'platform_version_value' + assert response.distribution == 'distribution_value' + assert response.cluster_region == 'cluster_region_value' + assert response.state == attached_resources.AttachedCluster.State.PROVISIONING + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.kubernetes_version == 'kubernetes_version_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attached_cluster_rest_interceptors(null_interceptor): + transport = transports.AttachedClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), + ) + client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_get_attached_cluster") as post, \ + mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_get_attached_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attached_service.GetAttachedClusterRequest.pb(attached_service.GetAttachedClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = attached_resources.AttachedCluster.to_json(attached_resources.AttachedCluster()) + req.return_value.content = return_value + + request = attached_service.GetAttachedClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attached_resources.AttachedCluster() + + client.get_attached_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_attached_clusters_rest_bad_request(request_type=attached_service.ListAttachedClustersRequest): + client = AttachedClustersClient( + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_attached_clusters(request) + + +@pytest.mark.parametrize("request_type", [ + attached_service.ListAttachedClustersRequest, + dict, +]) +def test_list_attached_clusters_rest_call_success(request_type): + client = AttachedClustersClient( + 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 = attached_service.ListAttachedClustersResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = attached_service.ListAttachedClustersResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_attached_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttachedClustersPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_attached_clusters_rest_interceptors(null_interceptor): + transport = transports.AttachedClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), + ) + client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_list_attached_clusters") as post, \ + mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_list_attached_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attached_service.ListAttachedClustersRequest.pb(attached_service.ListAttachedClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = attached_service.ListAttachedClustersResponse.to_json(attached_service.ListAttachedClustersResponse()) + req.return_value.content = return_value + + request = attached_service.ListAttachedClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attached_service.ListAttachedClustersResponse() + + client.list_attached_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_attached_cluster_rest_bad_request(request_type=attached_service.DeleteAttachedClusterRequest): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_attached_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + attached_service.DeleteAttachedClusterRequest, + dict, +]) +def test_delete_attached_cluster_rest_call_success(request_type): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_attached_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_attached_cluster_rest_interceptors(null_interceptor): + transport = transports.AttachedClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), + ) + client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_delete_attached_cluster") as post, \ + mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_delete_attached_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attached_service.DeleteAttachedClusterRequest.pb(attached_service.DeleteAttachedClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = attached_service.DeleteAttachedClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_attached_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_attached_server_config_rest_bad_request(request_type=attached_service.GetAttachedServerConfigRequest): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/attachedServerConfig'} + 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_attached_server_config(request) + + +@pytest.mark.parametrize("request_type", [ + attached_service.GetAttachedServerConfigRequest, + dict, +]) +def test_get_attached_server_config_rest_call_success(request_type): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/attachedServerConfig'} + 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 = attached_resources.AttachedServerConfig( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = attached_resources.AttachedServerConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_attached_server_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_resources.AttachedServerConfig) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attached_server_config_rest_interceptors(null_interceptor): + transport = transports.AttachedClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), + ) + client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_get_attached_server_config") as post, \ + mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_get_attached_server_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attached_service.GetAttachedServerConfigRequest.pb(attached_service.GetAttachedServerConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = attached_resources.AttachedServerConfig.to_json(attached_resources.AttachedServerConfig()) + req.return_value.content = return_value + + request = attached_service.GetAttachedServerConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attached_resources.AttachedServerConfig() + + client.get_attached_server_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_attached_cluster_install_manifest_rest_bad_request(request_type=attached_service.GenerateAttachedClusterInstallManifestRequest): + client = AttachedClustersClient( + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.generate_attached_cluster_install_manifest(request) + + +@pytest.mark.parametrize("request_type", [ + attached_service.GenerateAttachedClusterInstallManifestRequest, + dict, +]) +def test_generate_attached_cluster_install_manifest_rest_call_success(request_type): + client = AttachedClustersClient( + 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 = attached_service.GenerateAttachedClusterInstallManifestResponse( + manifest='manifest_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = attached_service.GenerateAttachedClusterInstallManifestResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.generate_attached_cluster_install_manifest(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_service.GenerateAttachedClusterInstallManifestResponse) + assert response.manifest == 'manifest_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_attached_cluster_install_manifest_rest_interceptors(null_interceptor): + transport = transports.AttachedClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), + ) + client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_generate_attached_cluster_install_manifest") as post, \ + mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_generate_attached_cluster_install_manifest") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attached_service.GenerateAttachedClusterInstallManifestRequest.pb(attached_service.GenerateAttachedClusterInstallManifestRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = attached_service.GenerateAttachedClusterInstallManifestResponse.to_json(attached_service.GenerateAttachedClusterInstallManifestResponse()) + req.return_value.content = return_value + + request = attached_service.GenerateAttachedClusterInstallManifestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() + + client.generate_attached_cluster_install_manifest(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_attached_cluster_agent_token_rest_bad_request(request_type=attached_service.GenerateAttachedClusterAgentTokenRequest): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'attached_cluster': 'projects/sample1/locations/sample2/attachedClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.generate_attached_cluster_agent_token(request) + + +@pytest.mark.parametrize("request_type", [ + attached_service.GenerateAttachedClusterAgentTokenRequest, + dict, +]) +def test_generate_attached_cluster_agent_token_rest_call_success(request_type): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'attached_cluster': 'projects/sample1/locations/sample2/attachedClusters/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 = attached_service.GenerateAttachedClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = attached_service.GenerateAttachedClusterAgentTokenResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.generate_attached_cluster_agent_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, attached_service.GenerateAttachedClusterAgentTokenResponse) + assert response.access_token == 'access_token_value' + assert response.expires_in == 1078 + assert response.token_type == 'token_type_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_attached_cluster_agent_token_rest_interceptors(null_interceptor): + transport = transports.AttachedClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), + ) + client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_generate_attached_cluster_agent_token") as post, \ + mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_generate_attached_cluster_agent_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attached_service.GenerateAttachedClusterAgentTokenRequest.pb(attached_service.GenerateAttachedClusterAgentTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = attached_service.GenerateAttachedClusterAgentTokenResponse.to_json(attached_service.GenerateAttachedClusterAgentTokenResponse()) + req.return_value.content = return_value + + request = attached_service.GenerateAttachedClusterAgentTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attached_service.GenerateAttachedClusterAgentTokenResponse() + + client.generate_attached_cluster_agent_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = AttachedClustersClient( + 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(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 = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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(request_type=operations_pb2.DeleteOperationRequest): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = AttachedClustersClient( + 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(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 = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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(request_type=operations_pb2.GetOperationRequest): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = AttachedClustersClient( + 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(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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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(request_type=operations_pb2.ListOperationsRequest): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = AttachedClustersClient( + 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(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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_initialize_client_w_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_attached_cluster_empty_call_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_attached_cluster), + '__call__') as call: + client.create_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.CreateAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_attached_cluster_empty_call_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attached_cluster), + '__call__') as call: + client.update_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.UpdateAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_attached_cluster_empty_call_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_attached_cluster), + '__call__') as call: + client.import_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.ImportAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_attached_cluster_empty_call_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_cluster), + '__call__') as call: + client.get_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GetAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_attached_clusters_empty_call_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_attached_clusters), + '__call__') as call: + client.list_attached_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.ListAttachedClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_attached_cluster_empty_call_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_attached_cluster), + '__call__') as call: + client.delete_attached_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.DeleteAttachedClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_attached_server_config_empty_call_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attached_server_config), + '__call__') as call: + client.get_attached_server_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GetAttachedServerConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_attached_cluster_install_manifest_empty_call_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_install_manifest), + '__call__') as call: + client.generate_attached_cluster_install_manifest(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GenerateAttachedClusterInstallManifestRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_attached_cluster_agent_token_empty_call_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_attached_cluster_agent_token), + '__call__') as call: + client.generate_attached_cluster_agent_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attached_service.GenerateAttachedClusterAgentTokenRequest() + + assert args[0] == request_msg + + +def test_attached_clusters_rest_lro_client(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an 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 + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AttachedClustersGrpcTransport, + ) + +def test_attached_clusters_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AttachedClustersTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_attached_clusters_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.gke_multicloud_v1.services.attached_clusters.transports.AttachedClustersTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AttachedClustersTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_attached_cluster', + 'update_attached_cluster', + 'import_attached_cluster', + 'get_attached_cluster', + 'list_attached_clusters', + 'delete_attached_cluster', + 'get_attached_server_config', + 'generate_attached_cluster_install_manifest', + 'generate_attached_cluster_agent_token', + '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_attached_clusters_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.gke_multicloud_v1.services.attached_clusters.transports.AttachedClustersTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AttachedClustersTransport( + 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_attached_clusters_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.gke_multicloud_v1.services.attached_clusters.transports.AttachedClustersTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AttachedClustersTransport() + adc.assert_called_once() + + +def test_attached_clusters_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) + AttachedClustersClient() + 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.AttachedClustersGrpcTransport, + transports.AttachedClustersGrpcAsyncIOTransport, + ], +) +def test_attached_clusters_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.AttachedClustersGrpcTransport, + transports.AttachedClustersGrpcAsyncIOTransport, + transports.AttachedClustersRestTransport, + ], +) +def test_attached_clusters_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.AttachedClustersGrpcTransport, grpc_helpers), + (transports.AttachedClustersGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_attached_clusters_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( + "gkemulticloud.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="gkemulticloud.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AttachedClustersGrpcTransport, transports.AttachedClustersGrpcAsyncIOTransport]) +def test_attached_clusters_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_attached_clusters_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.AttachedClustersRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_attached_clusters_host_no_port(transport_name): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'gkemulticloud.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://gkemulticloud.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_attached_clusters_host_with_port(transport_name): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'gkemulticloud.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://gkemulticloud.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_attached_clusters_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AttachedClustersClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AttachedClustersClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_attached_cluster._session + session2 = client2.transport.create_attached_cluster._session + assert session1 != session2 + session1 = client1.transport.update_attached_cluster._session + session2 = client2.transport.update_attached_cluster._session + assert session1 != session2 + session1 = client1.transport.import_attached_cluster._session + session2 = client2.transport.import_attached_cluster._session + assert session1 != session2 + session1 = client1.transport.get_attached_cluster._session + session2 = client2.transport.get_attached_cluster._session + assert session1 != session2 + session1 = client1.transport.list_attached_clusters._session + session2 = client2.transport.list_attached_clusters._session + assert session1 != session2 + session1 = client1.transport.delete_attached_cluster._session + session2 = client2.transport.delete_attached_cluster._session + assert session1 != session2 + session1 = client1.transport.get_attached_server_config._session + session2 = client2.transport.get_attached_server_config._session + assert session1 != session2 + session1 = client1.transport.generate_attached_cluster_install_manifest._session + session2 = client2.transport.generate_attached_cluster_install_manifest._session + assert session1 != session2 + session1 = client1.transport.generate_attached_cluster_agent_token._session + session2 = client2.transport.generate_attached_cluster_agent_token._session + assert session1 != session2 +def test_attached_clusters_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AttachedClustersGrpcTransport( + 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_attached_clusters_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AttachedClustersGrpcAsyncIOTransport( + 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.AttachedClustersGrpcTransport, transports.AttachedClustersGrpcAsyncIOTransport]) +def test_attached_clusters_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.AttachedClustersGrpcTransport, transports.AttachedClustersGrpcAsyncIOTransport]) +def test_attached_clusters_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_attached_clusters_grpc_lro_client(): + client = AttachedClustersClient( + 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_attached_clusters_grpc_lro_async_client(): + client = AttachedClustersAsyncClient( + 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_attached_cluster_path(): + project = "squid" + location = "clam" + attached_cluster = "whelk" + expected = "projects/{project}/locations/{location}/attachedClusters/{attached_cluster}".format(project=project, location=location, attached_cluster=attached_cluster, ) + actual = AttachedClustersClient.attached_cluster_path(project, location, attached_cluster) + assert expected == actual + + +def test_parse_attached_cluster_path(): + expected = { + "project": "octopus", + "location": "oyster", + "attached_cluster": "nudibranch", + } + path = AttachedClustersClient.attached_cluster_path(**expected) + + # Check that the path construction is reversible. + actual = AttachedClustersClient.parse_attached_cluster_path(path) + assert expected == actual + +def test_attached_server_config_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}/attachedServerConfig".format(project=project, location=location, ) + actual = AttachedClustersClient.attached_server_config_path(project, location) + assert expected == actual + + +def test_parse_attached_server_config_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = AttachedClustersClient.attached_server_config_path(**expected) + + # Check that the path construction is reversible. + actual = AttachedClustersClient.parse_attached_server_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AttachedClustersClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = AttachedClustersClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AttachedClustersClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = AttachedClustersClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = AttachedClustersClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AttachedClustersClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AttachedClustersClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = AttachedClustersClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AttachedClustersClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = AttachedClustersClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = AttachedClustersClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AttachedClustersClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AttachedClustersClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = AttachedClustersClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AttachedClustersClient.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.AttachedClustersTransport, '_prep_wrapped_messages') as prep: + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AttachedClustersTransport, '_prep_wrapped_messages') as prep: + transport_class = AttachedClustersClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = AttachedClustersClient( + 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_asyncio"): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AttachedClustersClient( + 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 = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AttachedClustersClient( + 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 = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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 = AttachedClustersClient( + 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_asyncio"): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AttachedClustersClient( + 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 = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AttachedClustersClient( + 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 = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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 = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AttachedClustersClient( + 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 = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AttachedClustersClient( + 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 = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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 = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AttachedClustersClient( + 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 = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AttachedClustersClient( + 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 = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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_transport_close_grpc(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AttachedClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_rest(): + client = AttachedClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "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 = AttachedClustersClient( + 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", [ + (AttachedClustersClient, transports.AttachedClustersGrpcTransport), + (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_aws_clusters.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_aws_clusters.py new file mode 100644 index 000000000000..bd60753cd32e --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_aws_clusters.py @@ -0,0 +1,13259 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.gke_multicloud_v1.services.aws_clusters import AwsClustersAsyncClient +from google.cloud.gke_multicloud_v1.services.aws_clusters import AwsClustersClient +from google.cloud.gke_multicloud_v1.services.aws_clusters import pagers +from google.cloud.gke_multicloud_v1.services.aws_clusters import transports +from google.cloud.gke_multicloud_v1.types import aws_resources +from google.cloud.gke_multicloud_v1.types import aws_service +from google.cloud.gke_multicloud_v1.types import common_resources +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 + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AwsClustersClient._get_default_mtls_endpoint(None) is None + assert AwsClustersClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AwsClustersClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AwsClustersClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AwsClustersClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AwsClustersClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AwsClustersClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AwsClustersClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AwsClustersClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AwsClustersClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert AwsClustersClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AwsClustersClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AwsClustersClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AwsClustersClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert AwsClustersClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert AwsClustersClient._get_client_cert_source(None, False) is None + assert AwsClustersClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AwsClustersClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert AwsClustersClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AwsClustersClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AwsClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersClient)) +@mock.patch.object(AwsClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AwsClustersClient._DEFAULT_UNIVERSE + default_endpoint = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AwsClustersClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AwsClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AwsClustersClient.DEFAULT_MTLS_ENDPOINT + assert AwsClustersClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AwsClustersClient._get_api_endpoint(None, None, default_universe, "always") == AwsClustersClient.DEFAULT_MTLS_ENDPOINT + assert AwsClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AwsClustersClient.DEFAULT_MTLS_ENDPOINT + assert AwsClustersClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AwsClustersClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AwsClustersClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert AwsClustersClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AwsClustersClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AwsClustersClient._get_universe_domain(None, None) == AwsClustersClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AwsClustersClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AwsClustersClient, "grpc"), + (AwsClustersAsyncClient, "grpc_asyncio"), + (AwsClustersClient, "rest"), +]) +def test_aws_clusters_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 == ( + 'gkemulticloud.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://gkemulticloud.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AwsClustersGrpcTransport, "grpc"), + (transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AwsClustersRestTransport, "rest"), +]) +def test_aws_clusters_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", [ + (AwsClustersClient, "grpc"), + (AwsClustersAsyncClient, "grpc_asyncio"), + (AwsClustersClient, "rest"), +]) +def test_aws_clusters_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 == ( + 'gkemulticloud.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://gkemulticloud.googleapis.com' + ) + + +def test_aws_clusters_client_get_transport_class(): + transport = AwsClustersClient.get_transport_class() + available_transports = [ + transports.AwsClustersGrpcTransport, + transports.AwsClustersRestTransport, + ] + assert transport in available_transports + + transport = AwsClustersClient.get_transport_class("grpc") + assert transport == transports.AwsClustersGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc"), + (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio"), + (AwsClustersClient, transports.AwsClustersRestTransport, "rest"), +]) +@mock.patch.object(AwsClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersClient)) +@mock.patch.object(AwsClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersAsyncClient)) +def test_aws_clusters_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(AwsClustersClient, '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(AwsClustersClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc", "true"), + (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc", "false"), + (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AwsClustersClient, transports.AwsClustersRestTransport, "rest", "true"), + (AwsClustersClient, transports.AwsClustersRestTransport, "rest", "false"), +]) +@mock.patch.object(AwsClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersClient)) +@mock.patch.object(AwsClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_aws_clusters_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + AwsClustersClient, AwsClustersAsyncClient +]) +@mock.patch.object(AwsClustersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AwsClustersClient)) +@mock.patch.object(AwsClustersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AwsClustersAsyncClient)) +def test_aws_clusters_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + AwsClustersClient, AwsClustersAsyncClient +]) +@mock.patch.object(AwsClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersClient)) +@mock.patch.object(AwsClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersAsyncClient)) +def test_aws_clusters_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AwsClustersClient._DEFAULT_UNIVERSE + default_endpoint = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc"), + (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio"), + (AwsClustersClient, transports.AwsClustersRestTransport, "rest"), +]) +def test_aws_clusters_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc", grpc_helpers), + (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AwsClustersClient, transports.AwsClustersRestTransport, "rest", None), +]) +def test_aws_clusters_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_aws_clusters_client_client_options_from_dict(): + with mock.patch('google.cloud.gke_multicloud_v1.services.aws_clusters.transports.AwsClustersGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AwsClustersClient( + 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", [ + (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc", grpc_helpers), + (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_aws_clusters_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "gkemulticloud.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="gkemulticloud.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + aws_service.CreateAwsClusterRequest, + dict, +]) +def test_create_aws_cluster(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.CreateAwsClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_aws_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.CreateAwsClusterRequest( + parent='parent_value', + aws_cluster_id='aws_cluster_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_aws_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.CreateAwsClusterRequest( + parent='parent_value', + aws_cluster_id='aws_cluster_id_value', + ) + +def test_create_aws_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_aws_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_aws_cluster] = mock_rpc + request = {} + client.create_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_aws_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_aws_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_aws_cluster] = mock_rpc + + request = {} + await client.create_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_aws_cluster_async(transport: str = 'grpc_asyncio', request_type=aws_service.CreateAwsClusterRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_cluster), + '__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_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.CreateAwsClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_aws_cluster_async_from_dict(): + await test_create_aws_cluster_async(request_type=dict) + +def test_create_aws_cluster_field_headers(): + client = AwsClustersClient( + 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 = aws_service.CreateAwsClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_aws_cluster(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_aws_cluster_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.CreateAwsClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_aws_cluster(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_aws_cluster_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_cluster), + '__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_aws_cluster( + parent='parent_value', + aws_cluster=aws_resources.AwsCluster(name='name_value'), + aws_cluster_id='aws_cluster_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].aws_cluster + mock_val = aws_resources.AwsCluster(name='name_value') + assert arg == mock_val + arg = args[0].aws_cluster_id + mock_val = 'aws_cluster_id_value' + assert arg == mock_val + + +def test_create_aws_cluster_flattened_error(): + client = AwsClustersClient( + 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_aws_cluster( + aws_service.CreateAwsClusterRequest(), + parent='parent_value', + aws_cluster=aws_resources.AwsCluster(name='name_value'), + aws_cluster_id='aws_cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_aws_cluster_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_cluster), + '__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_aws_cluster( + parent='parent_value', + aws_cluster=aws_resources.AwsCluster(name='name_value'), + aws_cluster_id='aws_cluster_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].aws_cluster + mock_val = aws_resources.AwsCluster(name='name_value') + assert arg == mock_val + arg = args[0].aws_cluster_id + mock_val = 'aws_cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_aws_cluster_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_aws_cluster( + aws_service.CreateAwsClusterRequest(), + parent='parent_value', + aws_cluster=aws_resources.AwsCluster(name='name_value'), + aws_cluster_id='aws_cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + aws_service.UpdateAwsClusterRequest, + dict, +]) +def test_update_aws_cluster(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.UpdateAwsClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_aws_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.UpdateAwsClusterRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_aws_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.UpdateAwsClusterRequest( + ) + +def test_update_aws_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_aws_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_aws_cluster] = mock_rpc + request = {} + client.update_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_aws_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_aws_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_aws_cluster] = mock_rpc + + request = {} + await client.update_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_aws_cluster_async(transport: str = 'grpc_asyncio', request_type=aws_service.UpdateAwsClusterRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_cluster), + '__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_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.UpdateAwsClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_aws_cluster_async_from_dict(): + await test_update_aws_cluster_async(request_type=dict) + +def test_update_aws_cluster_field_headers(): + client = AwsClustersClient( + 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 = aws_service.UpdateAwsClusterRequest() + + request.aws_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_aws_cluster(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', + 'aws_cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_aws_cluster_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.UpdateAwsClusterRequest() + + request.aws_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_aws_cluster(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', + 'aws_cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_aws_cluster_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_cluster), + '__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_aws_cluster( + aws_cluster=aws_resources.AwsCluster(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].aws_cluster + mock_val = aws_resources.AwsCluster(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_aws_cluster_flattened_error(): + client = AwsClustersClient( + 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_aws_cluster( + aws_service.UpdateAwsClusterRequest(), + aws_cluster=aws_resources.AwsCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_aws_cluster_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_cluster), + '__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_aws_cluster( + aws_cluster=aws_resources.AwsCluster(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].aws_cluster + mock_val = aws_resources.AwsCluster(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_aws_cluster_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_aws_cluster( + aws_service.UpdateAwsClusterRequest(), + aws_cluster=aws_resources.AwsCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GetAwsClusterRequest, + dict, +]) +def test_get_aws_cluster(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsCluster( + name='name_value', + description='description_value', + aws_region='aws_region_value', + state=aws_resources.AwsCluster.State.PROVISIONING, + endpoint='endpoint_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + cluster_ca_certificate='cluster_ca_certificate_value', + ) + response = client.get_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.GetAwsClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsCluster) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.aws_region == 'aws_region_value' + assert response.state == aws_resources.AwsCluster.State.PROVISIONING + assert response.endpoint == 'endpoint_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' + + +def test_get_aws_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.GetAwsClusterRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_aws_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.GetAwsClusterRequest( + name='name_value', + ) + +def test_get_aws_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_aws_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_aws_cluster] = mock_rpc + request = {} + client.get_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_aws_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_aws_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_aws_cluster] = mock_rpc + + request = {} + await client.get_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_aws_cluster_async(transport: str = 'grpc_asyncio', request_type=aws_service.GetAwsClusterRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsCluster( + name='name_value', + description='description_value', + aws_region='aws_region_value', + state=aws_resources.AwsCluster.State.PROVISIONING, + endpoint='endpoint_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + cluster_ca_certificate='cluster_ca_certificate_value', + )) + response = await client.get_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.GetAwsClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsCluster) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.aws_region == 'aws_region_value' + assert response.state == aws_resources.AwsCluster.State.PROVISIONING + assert response.endpoint == 'endpoint_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' + + +@pytest.mark.asyncio +async def test_get_aws_cluster_async_from_dict(): + await test_get_aws_cluster_async(request_type=dict) + +def test_get_aws_cluster_field_headers(): + client = AwsClustersClient( + 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 = aws_service.GetAwsClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_cluster), + '__call__') as call: + call.return_value = aws_resources.AwsCluster() + client.get_aws_cluster(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_aws_cluster_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.GetAwsClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsCluster()) + await client.get_aws_cluster(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_aws_cluster_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsCluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_aws_cluster( + 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_aws_cluster_flattened_error(): + client = AwsClustersClient( + 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_aws_cluster( + aws_service.GetAwsClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_aws_cluster_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsCluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsCluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_aws_cluster( + 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_aws_cluster_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_aws_cluster( + aws_service.GetAwsClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + aws_service.ListAwsClustersRequest, + dict, +]) +def test_list_aws_clusters(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_service.ListAwsClustersResponse( + next_page_token='next_page_token_value', + ) + response = client.list_aws_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.ListAwsClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAwsClustersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_aws_clusters_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.ListAwsClustersRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_clusters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_aws_clusters(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.ListAwsClustersRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_aws_clusters_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_aws_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_aws_clusters] = mock_rpc + request = {} + client.list_aws_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_aws_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_aws_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_aws_clusters in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_aws_clusters] = mock_rpc + + request = {} + await client.list_aws_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_aws_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_aws_clusters_async(transport: str = 'grpc_asyncio', request_type=aws_service.ListAwsClustersRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsClustersResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_aws_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.ListAwsClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAwsClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_aws_clusters_async_from_dict(): + await test_list_aws_clusters_async(request_type=dict) + +def test_list_aws_clusters_field_headers(): + client = AwsClustersClient( + 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 = aws_service.ListAwsClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_clusters), + '__call__') as call: + call.return_value = aws_service.ListAwsClustersResponse() + client.list_aws_clusters(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_aws_clusters_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.ListAwsClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsClustersResponse()) + await client.list_aws_clusters(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_aws_clusters_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_service.ListAwsClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_aws_clusters( + 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_aws_clusters_flattened_error(): + client = AwsClustersClient( + 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_aws_clusters( + aws_service.ListAwsClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_aws_clusters_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_service.ListAwsClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_aws_clusters( + 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_aws_clusters_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_aws_clusters( + aws_service.ListAwsClustersRequest(), + parent='parent_value', + ) + + +def test_list_aws_clusters_pager(transport_name: str = "grpc"): + client = AwsClustersClient( + 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_aws_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + ], + next_page_token='abc', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[], + next_page_token='def', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + ], + next_page_token='ghi', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_aws_clusters(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, aws_resources.AwsCluster) + for i in results) +def test_list_aws_clusters_pages(transport_name: str = "grpc"): + client = AwsClustersClient( + 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_aws_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + ], + next_page_token='abc', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[], + next_page_token='def', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + ], + next_page_token='ghi', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_aws_clusters(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_aws_clusters_async_pager(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + ], + next_page_token='abc', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[], + next_page_token='def', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + ], + next_page_token='ghi', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_aws_clusters(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, aws_resources.AwsCluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_aws_clusters_async_pages(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + ], + next_page_token='abc', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[], + next_page_token='def', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + ], + next_page_token='ghi', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + ], + ), + 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_aws_clusters(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", [ + aws_service.DeleteAwsClusterRequest, + dict, +]) +def test_delete_aws_cluster(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.DeleteAwsClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_aws_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.DeleteAwsClusterRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_aws_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.DeleteAwsClusterRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_aws_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_aws_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_aws_cluster] = mock_rpc + request = {} + client.delete_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_aws_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_aws_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_aws_cluster] = mock_rpc + + request = {} + await client.delete_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_aws_cluster_async(transport: str = 'grpc_asyncio', request_type=aws_service.DeleteAwsClusterRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_cluster), + '__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_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.DeleteAwsClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_aws_cluster_async_from_dict(): + await test_delete_aws_cluster_async(request_type=dict) + +def test_delete_aws_cluster_field_headers(): + client = AwsClustersClient( + 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 = aws_service.DeleteAwsClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_aws_cluster(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_aws_cluster_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.DeleteAwsClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_aws_cluster(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_aws_cluster_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_cluster), + '__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_aws_cluster( + 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_aws_cluster_flattened_error(): + client = AwsClustersClient( + 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_aws_cluster( + aws_service.DeleteAwsClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_aws_cluster_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_cluster), + '__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_aws_cluster( + 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_aws_cluster_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_aws_cluster( + aws_service.DeleteAwsClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GenerateAwsClusterAgentTokenRequest, + dict, +]) +def test_generate_aws_cluster_agent_token(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_cluster_agent_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_service.GenerateAwsClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + ) + response = client.generate_aws_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.GenerateAwsClusterAgentTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_service.GenerateAwsClusterAgentTokenResponse) + assert response.access_token == 'access_token_value' + assert response.expires_in == 1078 + assert response.token_type == 'token_type_value' + + +def test_generate_aws_cluster_agent_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.GenerateAwsClusterAgentTokenRequest( + aws_cluster='aws_cluster_value', + subject_token='subject_token_value', + subject_token_type='subject_token_type_value', + version='version_value', + node_pool_id='node_pool_id_value', + grant_type='grant_type_value', + audience='audience_value', + scope='scope_value', + requested_token_type='requested_token_type_value', + options='options_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_cluster_agent_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_aws_cluster_agent_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.GenerateAwsClusterAgentTokenRequest( + aws_cluster='aws_cluster_value', + subject_token='subject_token_value', + subject_token_type='subject_token_type_value', + version='version_value', + node_pool_id='node_pool_id_value', + grant_type='grant_type_value', + audience='audience_value', + scope='scope_value', + requested_token_type='requested_token_type_value', + options='options_value', + ) + +def test_generate_aws_cluster_agent_token_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_aws_cluster_agent_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_aws_cluster_agent_token] = mock_rpc + request = {} + client.generate_aws_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_aws_cluster_agent_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_aws_cluster_agent_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_aws_cluster_agent_token in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.generate_aws_cluster_agent_token] = mock_rpc + + request = {} + await client.generate_aws_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_aws_cluster_agent_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_aws_cluster_agent_token_async(transport: str = 'grpc_asyncio', request_type=aws_service.GenerateAwsClusterAgentTokenRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_cluster_agent_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + )) + response = await client.generate_aws_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.GenerateAwsClusterAgentTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_service.GenerateAwsClusterAgentTokenResponse) + assert response.access_token == 'access_token_value' + assert response.expires_in == 1078 + assert response.token_type == 'token_type_value' + + +@pytest.mark.asyncio +async def test_generate_aws_cluster_agent_token_async_from_dict(): + await test_generate_aws_cluster_agent_token_async(request_type=dict) + +def test_generate_aws_cluster_agent_token_field_headers(): + client = AwsClustersClient( + 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 = aws_service.GenerateAwsClusterAgentTokenRequest() + + request.aws_cluster = 'aws_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_cluster_agent_token), + '__call__') as call: + call.return_value = aws_service.GenerateAwsClusterAgentTokenResponse() + client.generate_aws_cluster_agent_token(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', + 'aws_cluster=aws_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_aws_cluster_agent_token_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.GenerateAwsClusterAgentTokenRequest() + + request.aws_cluster = 'aws_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_cluster_agent_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsClusterAgentTokenResponse()) + await client.generate_aws_cluster_agent_token(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', + 'aws_cluster=aws_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + aws_service.GenerateAwsAccessTokenRequest, + dict, +]) +def test_generate_aws_access_token(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_service.GenerateAwsAccessTokenResponse( + access_token='access_token_value', + ) + response = client.generate_aws_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.GenerateAwsAccessTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_service.GenerateAwsAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +def test_generate_aws_access_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.GenerateAwsAccessTokenRequest( + aws_cluster='aws_cluster_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_access_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_aws_access_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.GenerateAwsAccessTokenRequest( + aws_cluster='aws_cluster_value', + ) + +def test_generate_aws_access_token_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_aws_access_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_aws_access_token] = mock_rpc + request = {} + client.generate_aws_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_aws_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_aws_access_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_aws_access_token in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.generate_aws_access_token] = mock_rpc + + request = {} + await client.generate_aws_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_aws_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_aws_access_token_async(transport: str = 'grpc_asyncio', request_type=aws_service.GenerateAwsAccessTokenRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsAccessTokenResponse( + access_token='access_token_value', + )) + response = await client.generate_aws_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.GenerateAwsAccessTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_service.GenerateAwsAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +@pytest.mark.asyncio +async def test_generate_aws_access_token_async_from_dict(): + await test_generate_aws_access_token_async(request_type=dict) + +def test_generate_aws_access_token_field_headers(): + client = AwsClustersClient( + 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 = aws_service.GenerateAwsAccessTokenRequest() + + request.aws_cluster = 'aws_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_access_token), + '__call__') as call: + call.return_value = aws_service.GenerateAwsAccessTokenResponse() + client.generate_aws_access_token(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', + 'aws_cluster=aws_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_aws_access_token_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.GenerateAwsAccessTokenRequest() + + request.aws_cluster = 'aws_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_access_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsAccessTokenResponse()) + await client.generate_aws_access_token(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', + 'aws_cluster=aws_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + aws_service.CreateAwsNodePoolRequest, + dict, +]) +def test_create_aws_node_pool(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.CreateAwsNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_aws_node_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.CreateAwsNodePoolRequest( + parent='parent_value', + aws_node_pool_id='aws_node_pool_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_node_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_aws_node_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.CreateAwsNodePoolRequest( + parent='parent_value', + aws_node_pool_id='aws_node_pool_id_value', + ) + +def test_create_aws_node_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_aws_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_aws_node_pool] = mock_rpc + request = {} + client.create_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_aws_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_aws_node_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_aws_node_pool] = mock_rpc + + request = {} + await client.create_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_aws_node_pool_async(transport: str = 'grpc_asyncio', request_type=aws_service.CreateAwsNodePoolRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_node_pool), + '__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_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.CreateAwsNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_aws_node_pool_async_from_dict(): + await test_create_aws_node_pool_async(request_type=dict) + +def test_create_aws_node_pool_field_headers(): + client = AwsClustersClient( + 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 = aws_service.CreateAwsNodePoolRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_aws_node_pool(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_aws_node_pool_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.CreateAwsNodePoolRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_node_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_aws_node_pool(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_aws_node_pool_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_node_pool), + '__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_aws_node_pool( + parent='parent_value', + aws_node_pool=aws_resources.AwsNodePool(name='name_value'), + aws_node_pool_id='aws_node_pool_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].aws_node_pool + mock_val = aws_resources.AwsNodePool(name='name_value') + assert arg == mock_val + arg = args[0].aws_node_pool_id + mock_val = 'aws_node_pool_id_value' + assert arg == mock_val + + +def test_create_aws_node_pool_flattened_error(): + client = AwsClustersClient( + 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_aws_node_pool( + aws_service.CreateAwsNodePoolRequest(), + parent='parent_value', + aws_node_pool=aws_resources.AwsNodePool(name='name_value'), + aws_node_pool_id='aws_node_pool_id_value', + ) + +@pytest.mark.asyncio +async def test_create_aws_node_pool_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_node_pool), + '__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_aws_node_pool( + parent='parent_value', + aws_node_pool=aws_resources.AwsNodePool(name='name_value'), + aws_node_pool_id='aws_node_pool_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].aws_node_pool + mock_val = aws_resources.AwsNodePool(name='name_value') + assert arg == mock_val + arg = args[0].aws_node_pool_id + mock_val = 'aws_node_pool_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_aws_node_pool_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_aws_node_pool( + aws_service.CreateAwsNodePoolRequest(), + parent='parent_value', + aws_node_pool=aws_resources.AwsNodePool(name='name_value'), + aws_node_pool_id='aws_node_pool_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + aws_service.UpdateAwsNodePoolRequest, + dict, +]) +def test_update_aws_node_pool(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.UpdateAwsNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_aws_node_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.UpdateAwsNodePoolRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_node_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_aws_node_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.UpdateAwsNodePoolRequest( + ) + +def test_update_aws_node_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_aws_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_aws_node_pool] = mock_rpc + request = {} + client.update_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_aws_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_aws_node_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_aws_node_pool] = mock_rpc + + request = {} + await client.update_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_aws_node_pool_async(transport: str = 'grpc_asyncio', request_type=aws_service.UpdateAwsNodePoolRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_node_pool), + '__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_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.UpdateAwsNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_aws_node_pool_async_from_dict(): + await test_update_aws_node_pool_async(request_type=dict) + +def test_update_aws_node_pool_field_headers(): + client = AwsClustersClient( + 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 = aws_service.UpdateAwsNodePoolRequest() + + request.aws_node_pool.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_aws_node_pool(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', + 'aws_node_pool.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_aws_node_pool_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.UpdateAwsNodePoolRequest() + + request.aws_node_pool.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_node_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_aws_node_pool(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', + 'aws_node_pool.name=name_value', + ) in kw['metadata'] + + +def test_update_aws_node_pool_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_node_pool), + '__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_aws_node_pool( + aws_node_pool=aws_resources.AwsNodePool(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].aws_node_pool + mock_val = aws_resources.AwsNodePool(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_aws_node_pool_flattened_error(): + client = AwsClustersClient( + 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_aws_node_pool( + aws_service.UpdateAwsNodePoolRequest(), + aws_node_pool=aws_resources.AwsNodePool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_aws_node_pool_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_node_pool), + '__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_aws_node_pool( + aws_node_pool=aws_resources.AwsNodePool(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].aws_node_pool + mock_val = aws_resources.AwsNodePool(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_aws_node_pool_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_aws_node_pool( + aws_service.UpdateAwsNodePoolRequest(), + aws_node_pool=aws_resources.AwsNodePool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + aws_service.RollbackAwsNodePoolUpdateRequest, + dict, +]) +def test_rollback_aws_node_pool_update(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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.rollback_aws_node_pool_update), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.rollback_aws_node_pool_update(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.RollbackAwsNodePoolUpdateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_rollback_aws_node_pool_update_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.RollbackAwsNodePoolUpdateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rollback_aws_node_pool_update), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.rollback_aws_node_pool_update(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.RollbackAwsNodePoolUpdateRequest( + name='name_value', + ) + +def test_rollback_aws_node_pool_update_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.rollback_aws_node_pool_update in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.rollback_aws_node_pool_update] = mock_rpc + request = {} + client.rollback_aws_node_pool_update(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.rollback_aws_node_pool_update(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_rollback_aws_node_pool_update_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.rollback_aws_node_pool_update in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.rollback_aws_node_pool_update] = mock_rpc + + request = {} + await client.rollback_aws_node_pool_update(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.rollback_aws_node_pool_update(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_rollback_aws_node_pool_update_async(transport: str = 'grpc_asyncio', request_type=aws_service.RollbackAwsNodePoolUpdateRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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.rollback_aws_node_pool_update), + '__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.rollback_aws_node_pool_update(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.RollbackAwsNodePoolUpdateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_rollback_aws_node_pool_update_async_from_dict(): + await test_rollback_aws_node_pool_update_async(request_type=dict) + +def test_rollback_aws_node_pool_update_field_headers(): + client = AwsClustersClient( + 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 = aws_service.RollbackAwsNodePoolUpdateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rollback_aws_node_pool_update), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rollback_aws_node_pool_update(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_rollback_aws_node_pool_update_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.RollbackAwsNodePoolUpdateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rollback_aws_node_pool_update), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.rollback_aws_node_pool_update(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_rollback_aws_node_pool_update_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rollback_aws_node_pool_update), + '__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.rollback_aws_node_pool_update( + 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_rollback_aws_node_pool_update_flattened_error(): + client = AwsClustersClient( + 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.rollback_aws_node_pool_update( + aws_service.RollbackAwsNodePoolUpdateRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_rollback_aws_node_pool_update_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rollback_aws_node_pool_update), + '__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.rollback_aws_node_pool_update( + 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_rollback_aws_node_pool_update_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.rollback_aws_node_pool_update( + aws_service.RollbackAwsNodePoolUpdateRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GetAwsNodePoolRequest, + dict, +]) +def test_get_aws_node_pool(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsNodePool( + name='name_value', + version='version_value', + subnet_id='subnet_id_value', + state=aws_resources.AwsNodePool.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + ) + response = client.get_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.GetAwsNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsNodePool) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.subnet_id == 'subnet_id_value' + assert response.state == aws_resources.AwsNodePool.State.PROVISIONING + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + + +def test_get_aws_node_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.GetAwsNodePoolRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_node_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_aws_node_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.GetAwsNodePoolRequest( + name='name_value', + ) + +def test_get_aws_node_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_aws_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_aws_node_pool] = mock_rpc + request = {} + client.get_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_aws_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_aws_node_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_aws_node_pool] = mock_rpc + + request = {} + await client.get_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_aws_node_pool_async(transport: str = 'grpc_asyncio', request_type=aws_service.GetAwsNodePoolRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsNodePool( + name='name_value', + version='version_value', + subnet_id='subnet_id_value', + state=aws_resources.AwsNodePool.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + )) + response = await client.get_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.GetAwsNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsNodePool) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.subnet_id == 'subnet_id_value' + assert response.state == aws_resources.AwsNodePool.State.PROVISIONING + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_aws_node_pool_async_from_dict(): + await test_get_aws_node_pool_async(request_type=dict) + +def test_get_aws_node_pool_field_headers(): + client = AwsClustersClient( + 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 = aws_service.GetAwsNodePoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_node_pool), + '__call__') as call: + call.return_value = aws_resources.AwsNodePool() + client.get_aws_node_pool(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_aws_node_pool_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.GetAwsNodePoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_node_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsNodePool()) + await client.get_aws_node_pool(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_aws_node_pool_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsNodePool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_aws_node_pool( + 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_aws_node_pool_flattened_error(): + client = AwsClustersClient( + 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_aws_node_pool( + aws_service.GetAwsNodePoolRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_aws_node_pool_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsNodePool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsNodePool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_aws_node_pool( + 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_aws_node_pool_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_aws_node_pool( + aws_service.GetAwsNodePoolRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + aws_service.ListAwsNodePoolsRequest, + dict, +]) +def test_list_aws_node_pools(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_node_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_service.ListAwsNodePoolsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_aws_node_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.ListAwsNodePoolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAwsNodePoolsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_aws_node_pools_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.ListAwsNodePoolsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_node_pools), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_aws_node_pools(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.ListAwsNodePoolsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_aws_node_pools_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_aws_node_pools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_aws_node_pools] = mock_rpc + request = {} + client.list_aws_node_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_aws_node_pools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_aws_node_pools_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_aws_node_pools in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_aws_node_pools] = mock_rpc + + request = {} + await client.list_aws_node_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_aws_node_pools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_aws_node_pools_async(transport: str = 'grpc_asyncio', request_type=aws_service.ListAwsNodePoolsRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_node_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsNodePoolsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_aws_node_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.ListAwsNodePoolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAwsNodePoolsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_aws_node_pools_async_from_dict(): + await test_list_aws_node_pools_async(request_type=dict) + +def test_list_aws_node_pools_field_headers(): + client = AwsClustersClient( + 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 = aws_service.ListAwsNodePoolsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_node_pools), + '__call__') as call: + call.return_value = aws_service.ListAwsNodePoolsResponse() + client.list_aws_node_pools(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_aws_node_pools_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.ListAwsNodePoolsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_node_pools), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsNodePoolsResponse()) + await client.list_aws_node_pools(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_aws_node_pools_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_node_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_service.ListAwsNodePoolsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_aws_node_pools( + 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_aws_node_pools_flattened_error(): + client = AwsClustersClient( + 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_aws_node_pools( + aws_service.ListAwsNodePoolsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_aws_node_pools_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_node_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_service.ListAwsNodePoolsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsNodePoolsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_aws_node_pools( + 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_aws_node_pools_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_aws_node_pools( + aws_service.ListAwsNodePoolsRequest(), + parent='parent_value', + ) + + +def test_list_aws_node_pools_pager(transport_name: str = "grpc"): + client = AwsClustersClient( + 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_aws_node_pools), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + ], + next_page_token='abc', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[], + next_page_token='def', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + ], + next_page_token='ghi', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_aws_node_pools(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, aws_resources.AwsNodePool) + for i in results) +def test_list_aws_node_pools_pages(transport_name: str = "grpc"): + client = AwsClustersClient( + 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_aws_node_pools), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + ], + next_page_token='abc', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[], + next_page_token='def', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + ], + next_page_token='ghi', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + ], + ), + RuntimeError, + ) + pages = list(client.list_aws_node_pools(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_aws_node_pools_async_pager(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_node_pools), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + ], + next_page_token='abc', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[], + next_page_token='def', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + ], + next_page_token='ghi', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_aws_node_pools(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, aws_resources.AwsNodePool) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_aws_node_pools_async_pages(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_node_pools), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + ], + next_page_token='abc', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[], + next_page_token='def', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + ], + next_page_token='ghi', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + ], + ), + 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_aws_node_pools(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", [ + aws_service.DeleteAwsNodePoolRequest, + dict, +]) +def test_delete_aws_node_pool(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.DeleteAwsNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_aws_node_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.DeleteAwsNodePoolRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_node_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_aws_node_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.DeleteAwsNodePoolRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_aws_node_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_aws_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_aws_node_pool] = mock_rpc + request = {} + client.delete_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_aws_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_aws_node_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_aws_node_pool] = mock_rpc + + request = {} + await client.delete_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_aws_node_pool_async(transport: str = 'grpc_asyncio', request_type=aws_service.DeleteAwsNodePoolRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_node_pool), + '__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_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.DeleteAwsNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_aws_node_pool_async_from_dict(): + await test_delete_aws_node_pool_async(request_type=dict) + +def test_delete_aws_node_pool_field_headers(): + client = AwsClustersClient( + 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 = aws_service.DeleteAwsNodePoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_aws_node_pool(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_aws_node_pool_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.DeleteAwsNodePoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_node_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_aws_node_pool(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_aws_node_pool_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_node_pool), + '__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_aws_node_pool( + 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_aws_node_pool_flattened_error(): + client = AwsClustersClient( + 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_aws_node_pool( + aws_service.DeleteAwsNodePoolRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_aws_node_pool_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_node_pool), + '__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_aws_node_pool( + 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_aws_node_pool_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_aws_node_pool( + aws_service.DeleteAwsNodePoolRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GetAwsOpenIdConfigRequest, + dict, +]) +def test_get_aws_open_id_config(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_open_id_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsOpenIdConfig( + issuer='issuer_value', + jwks_uri='jwks_uri_value', + response_types_supported=['response_types_supported_value'], + subject_types_supported=['subject_types_supported_value'], + id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], + claims_supported=['claims_supported_value'], + grant_types=['grant_types_value'], + ) + response = client.get_aws_open_id_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.GetAwsOpenIdConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsOpenIdConfig) + assert response.issuer == 'issuer_value' + assert response.jwks_uri == 'jwks_uri_value' + assert response.response_types_supported == ['response_types_supported_value'] + assert response.subject_types_supported == ['subject_types_supported_value'] + assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] + assert response.claims_supported == ['claims_supported_value'] + assert response.grant_types == ['grant_types_value'] + + +def test_get_aws_open_id_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.GetAwsOpenIdConfigRequest( + aws_cluster='aws_cluster_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_open_id_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_aws_open_id_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.GetAwsOpenIdConfigRequest( + aws_cluster='aws_cluster_value', + ) + +def test_get_aws_open_id_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_aws_open_id_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_aws_open_id_config] = mock_rpc + request = {} + client.get_aws_open_id_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_aws_open_id_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_aws_open_id_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_aws_open_id_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_aws_open_id_config] = mock_rpc + + request = {} + await client.get_aws_open_id_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_aws_open_id_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_aws_open_id_config_async(transport: str = 'grpc_asyncio', request_type=aws_service.GetAwsOpenIdConfigRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_open_id_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsOpenIdConfig( + issuer='issuer_value', + jwks_uri='jwks_uri_value', + response_types_supported=['response_types_supported_value'], + subject_types_supported=['subject_types_supported_value'], + id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], + claims_supported=['claims_supported_value'], + grant_types=['grant_types_value'], + )) + response = await client.get_aws_open_id_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.GetAwsOpenIdConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsOpenIdConfig) + assert response.issuer == 'issuer_value' + assert response.jwks_uri == 'jwks_uri_value' + assert response.response_types_supported == ['response_types_supported_value'] + assert response.subject_types_supported == ['subject_types_supported_value'] + assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] + assert response.claims_supported == ['claims_supported_value'] + assert response.grant_types == ['grant_types_value'] + + +@pytest.mark.asyncio +async def test_get_aws_open_id_config_async_from_dict(): + await test_get_aws_open_id_config_async(request_type=dict) + +def test_get_aws_open_id_config_field_headers(): + client = AwsClustersClient( + 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 = aws_service.GetAwsOpenIdConfigRequest() + + request.aws_cluster = 'aws_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_open_id_config), + '__call__') as call: + call.return_value = aws_resources.AwsOpenIdConfig() + client.get_aws_open_id_config(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', + 'aws_cluster=aws_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_aws_open_id_config_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.GetAwsOpenIdConfigRequest() + + request.aws_cluster = 'aws_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_open_id_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsOpenIdConfig()) + await client.get_aws_open_id_config(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', + 'aws_cluster=aws_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + aws_service.GetAwsJsonWebKeysRequest, + dict, +]) +def test_get_aws_json_web_keys(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_json_web_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsJsonWebKeys( + ) + response = client.get_aws_json_web_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.GetAwsJsonWebKeysRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsJsonWebKeys) + + +def test_get_aws_json_web_keys_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.GetAwsJsonWebKeysRequest( + aws_cluster='aws_cluster_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_json_web_keys), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_aws_json_web_keys(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.GetAwsJsonWebKeysRequest( + aws_cluster='aws_cluster_value', + ) + +def test_get_aws_json_web_keys_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_aws_json_web_keys in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_aws_json_web_keys] = mock_rpc + request = {} + client.get_aws_json_web_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_aws_json_web_keys(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_aws_json_web_keys_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_aws_json_web_keys in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_aws_json_web_keys] = mock_rpc + + request = {} + await client.get_aws_json_web_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_aws_json_web_keys(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_aws_json_web_keys_async(transport: str = 'grpc_asyncio', request_type=aws_service.GetAwsJsonWebKeysRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_json_web_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsJsonWebKeys( + )) + response = await client.get_aws_json_web_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.GetAwsJsonWebKeysRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsJsonWebKeys) + + +@pytest.mark.asyncio +async def test_get_aws_json_web_keys_async_from_dict(): + await test_get_aws_json_web_keys_async(request_type=dict) + +def test_get_aws_json_web_keys_field_headers(): + client = AwsClustersClient( + 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 = aws_service.GetAwsJsonWebKeysRequest() + + request.aws_cluster = 'aws_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_json_web_keys), + '__call__') as call: + call.return_value = aws_resources.AwsJsonWebKeys() + client.get_aws_json_web_keys(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', + 'aws_cluster=aws_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_aws_json_web_keys_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.GetAwsJsonWebKeysRequest() + + request.aws_cluster = 'aws_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_json_web_keys), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsJsonWebKeys()) + await client.get_aws_json_web_keys(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', + 'aws_cluster=aws_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + aws_service.GetAwsServerConfigRequest, + dict, +]) +def test_get_aws_server_config(request_type, transport: str = 'grpc'): + client = AwsClustersClient( + 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_aws_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsServerConfig( + name='name_value', + supported_aws_regions=['supported_aws_regions_value'], + ) + response = client.get_aws_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = aws_service.GetAwsServerConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsServerConfig) + assert response.name == 'name_value' + assert response.supported_aws_regions == ['supported_aws_regions_value'] + + +def test_get_aws_server_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = aws_service.GetAwsServerConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_server_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_aws_server_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == aws_service.GetAwsServerConfigRequest( + name='name_value', + ) + +def test_get_aws_server_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_aws_server_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_aws_server_config] = mock_rpc + request = {} + client.get_aws_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_aws_server_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_aws_server_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_aws_server_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_aws_server_config] = mock_rpc + + request = {} + await client.get_aws_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_aws_server_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_aws_server_config_async(transport: str = 'grpc_asyncio', request_type=aws_service.GetAwsServerConfigRequest): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_aws_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsServerConfig( + name='name_value', + supported_aws_regions=['supported_aws_regions_value'], + )) + response = await client.get_aws_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = aws_service.GetAwsServerConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsServerConfig) + assert response.name == 'name_value' + assert response.supported_aws_regions == ['supported_aws_regions_value'] + + +@pytest.mark.asyncio +async def test_get_aws_server_config_async_from_dict(): + await test_get_aws_server_config_async(request_type=dict) + +def test_get_aws_server_config_field_headers(): + client = AwsClustersClient( + 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 = aws_service.GetAwsServerConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_server_config), + '__call__') as call: + call.return_value = aws_resources.AwsServerConfig() + client.get_aws_server_config(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_aws_server_config_field_headers_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = aws_service.GetAwsServerConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_server_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsServerConfig()) + await client.get_aws_server_config(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_aws_server_config_flattened(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsServerConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_aws_server_config( + 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_aws_server_config_flattened_error(): + client = AwsClustersClient( + 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_aws_server_config( + aws_service.GetAwsServerConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_aws_server_config_flattened_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = aws_resources.AwsServerConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsServerConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_aws_server_config( + 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_aws_server_config_flattened_error_async(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_aws_server_config( + aws_service.GetAwsServerConfigRequest(), + name='name_value', + ) + + +def test_create_aws_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_aws_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_aws_cluster] = mock_rpc + + request = {} + client.create_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_aws_cluster_rest_required_fields(request_type=aws_service.CreateAwsClusterRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["aws_cluster_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "awsClusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_aws_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "awsClusterId" in jsonified_request + assert jsonified_request["awsClusterId"] == request_init["aws_cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["awsClusterId"] = 'aws_cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_aws_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("aws_cluster_id", "validate_only", )) + 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 "awsClusterId" in jsonified_request + assert jsonified_request["awsClusterId"] == 'aws_cluster_id_value' + + client = AwsClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_aws_cluster(request) + + expected_params = [ + ( + "awsClusterId", + "", + ), + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_aws_cluster_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_aws_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("awsClusterId", "validateOnly", )) & set(("parent", "awsCluster", "awsClusterId", ))) + + +def test_create_aws_cluster_rest_flattened(): + client = AwsClustersClient( + 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', + aws_cluster=aws_resources.AwsCluster(name='name_value'), + aws_cluster_id='aws_cluster_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_aws_cluster(**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/*}/awsClusters" % client.transport._host, args[1]) + + +def test_create_aws_cluster_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_cluster( + aws_service.CreateAwsClusterRequest(), + parent='parent_value', + aws_cluster=aws_resources.AwsCluster(name='name_value'), + aws_cluster_id='aws_cluster_id_value', + ) + + +def test_update_aws_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_aws_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_aws_cluster] = mock_rpc + + request = {} + client.update_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_aws_cluster_rest_required_fields(request_type=aws_service.UpdateAwsClusterRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_aws_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_aws_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AwsClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_aws_cluster(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_aws_cluster_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_aws_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("awsCluster", "updateMask", ))) + + +def test_update_aws_cluster_rest_flattened(): + client = AwsClustersClient( + 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 = {'aws_cluster': {'name': 'projects/sample1/locations/sample2/awsClusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + aws_cluster=aws_resources.AwsCluster(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_aws_cluster(**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/{aws_cluster.name=projects/*/locations/*/awsClusters/*}" % client.transport._host, args[1]) + + +def test_update_aws_cluster_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_cluster( + aws_service.UpdateAwsClusterRequest(), + aws_cluster=aws_resources.AwsCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_aws_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_aws_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_aws_cluster] = mock_rpc + + request = {} + client.get_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_aws_cluster_rest_required_fields(request_type=aws_service.GetAwsClusterRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_cluster._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_aws_cluster._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 = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = aws_resources.AwsCluster() + # 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 = aws_resources.AwsCluster.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_aws_cluster(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_aws_cluster_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_aws_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_aws_cluster_rest_flattened(): + client = AwsClustersClient( + 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 = aws_resources.AwsCluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/awsClusters/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 = aws_resources.AwsCluster.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_aws_cluster(**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/*/awsClusters/*}" % client.transport._host, args[1]) + + +def test_get_aws_cluster_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_cluster( + aws_service.GetAwsClusterRequest(), + name='name_value', + ) + + +def test_list_aws_clusters_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_aws_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_aws_clusters] = mock_rpc + + request = {} + client.list_aws_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_aws_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_aws_clusters_rest_required_fields(request_type=aws_service.ListAwsClustersRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_aws_clusters._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_aws_clusters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + 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 = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = aws_service.ListAwsClustersResponse() + # 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 = aws_service.ListAwsClustersResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_aws_clusters(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_aws_clusters_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_aws_clusters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_aws_clusters_rest_flattened(): + client = AwsClustersClient( + 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 = aws_service.ListAwsClustersResponse() + + # 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 = aws_service.ListAwsClustersResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_aws_clusters(**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/*}/awsClusters" % client.transport._host, args[1]) + + +def test_list_aws_clusters_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_clusters( + aws_service.ListAwsClustersRequest(), + parent='parent_value', + ) + + +def test_list_aws_clusters_rest_pager(transport: str = 'rest'): + client = AwsClustersClient( + 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 = ( + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + ], + next_page_token='abc', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[], + next_page_token='def', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + ], + next_page_token='ghi', + ), + aws_service.ListAwsClustersResponse( + aws_clusters=[ + aws_resources.AwsCluster(), + aws_resources.AwsCluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(aws_service.ListAwsClustersResponse.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_aws_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, aws_resources.AwsCluster) + for i in results) + + pages = list(client.list_aws_clusters(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_aws_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_aws_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_aws_cluster] = mock_rpc + + request = {} + client.delete_aws_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_aws_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_aws_cluster_rest_required_fields(request_type=aws_service.DeleteAwsClusterRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_aws_cluster._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_aws_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "etag", "ignore_errors", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AwsClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_aws_cluster(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_aws_cluster_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_aws_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "etag", "ignoreErrors", "validateOnly", )) & set(("name", ))) + + +def test_delete_aws_cluster_rest_flattened(): + client = AwsClustersClient( + 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/awsClusters/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_aws_cluster(**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/*/awsClusters/*}" % client.transport._host, args[1]) + + +def test_delete_aws_cluster_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_cluster( + aws_service.DeleteAwsClusterRequest(), + name='name_value', + ) + + +def test_generate_aws_cluster_agent_token_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_aws_cluster_agent_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_aws_cluster_agent_token] = mock_rpc + + request = {} + client.generate_aws_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_aws_cluster_agent_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_aws_cluster_agent_token_rest_required_fields(request_type=aws_service.GenerateAwsClusterAgentTokenRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["aws_cluster"] = "" + request_init["subject_token"] = "" + request_init["subject_token_type"] = "" + request_init["version"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_aws_cluster_agent_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["awsCluster"] = 'aws_cluster_value' + jsonified_request["subjectToken"] = 'subject_token_value' + jsonified_request["subjectTokenType"] = 'subject_token_type_value' + jsonified_request["version"] = 'version_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_aws_cluster_agent_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "awsCluster" in jsonified_request + assert jsonified_request["awsCluster"] == 'aws_cluster_value' + assert "subjectToken" in jsonified_request + assert jsonified_request["subjectToken"] == 'subject_token_value' + assert "subjectTokenType" in jsonified_request + assert jsonified_request["subjectTokenType"] == 'subject_token_type_value' + assert "version" in jsonified_request + assert jsonified_request["version"] == 'version_value' + + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = aws_service.GenerateAwsClusterAgentTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = aws_service.GenerateAwsClusterAgentTokenResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_aws_cluster_agent_token(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_aws_cluster_agent_token_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_aws_cluster_agent_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("awsCluster", "subjectToken", "subjectTokenType", "version", ))) + + +def test_generate_aws_access_token_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_aws_access_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_aws_access_token] = mock_rpc + + request = {} + client.generate_aws_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_aws_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_aws_access_token_rest_required_fields(request_type=aws_service.GenerateAwsAccessTokenRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["aws_cluster"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_aws_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["awsCluster"] = 'aws_cluster_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_aws_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "awsCluster" in jsonified_request + assert jsonified_request["awsCluster"] == 'aws_cluster_value' + + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = aws_service.GenerateAwsAccessTokenResponse() + # 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 = aws_service.GenerateAwsAccessTokenResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_aws_access_token(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_aws_access_token_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_aws_access_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("awsCluster", ))) + + +def test_create_aws_node_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_aws_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_aws_node_pool] = mock_rpc + + request = {} + client.create_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_aws_node_pool_rest_required_fields(request_type=aws_service.CreateAwsNodePoolRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["aws_node_pool_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "awsNodePoolId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_aws_node_pool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "awsNodePoolId" in jsonified_request + assert jsonified_request["awsNodePoolId"] == request_init["aws_node_pool_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["awsNodePoolId"] = 'aws_node_pool_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_aws_node_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("aws_node_pool_id", "validate_only", )) + 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 "awsNodePoolId" in jsonified_request + assert jsonified_request["awsNodePoolId"] == 'aws_node_pool_id_value' + + client = AwsClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_aws_node_pool(request) + + expected_params = [ + ( + "awsNodePoolId", + "", + ), + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_aws_node_pool_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_aws_node_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("awsNodePoolId", "validateOnly", )) & set(("parent", "awsNodePool", "awsNodePoolId", ))) + + +def test_create_aws_node_pool_rest_flattened(): + client = AwsClustersClient( + 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/awsClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + aws_node_pool=aws_resources.AwsNodePool(name='name_value'), + aws_node_pool_id='aws_node_pool_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_aws_node_pool(**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/*/awsClusters/*}/awsNodePools" % client.transport._host, args[1]) + + +def test_create_aws_node_pool_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_node_pool( + aws_service.CreateAwsNodePoolRequest(), + parent='parent_value', + aws_node_pool=aws_resources.AwsNodePool(name='name_value'), + aws_node_pool_id='aws_node_pool_id_value', + ) + + +def test_update_aws_node_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_aws_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_aws_node_pool] = mock_rpc + + request = {} + client.update_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_aws_node_pool_rest_required_fields(request_type=aws_service.UpdateAwsNodePoolRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_aws_node_pool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_aws_node_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AwsClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_aws_node_pool(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_aws_node_pool_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_aws_node_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("awsNodePool", "updateMask", ))) + + +def test_update_aws_node_pool_rest_flattened(): + client = AwsClustersClient( + 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 = {'aws_node_pool': {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + aws_node_pool=aws_resources.AwsNodePool(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_aws_node_pool(**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/{aws_node_pool.name=projects/*/locations/*/awsClusters/*/awsNodePools/*}" % client.transport._host, args[1]) + + +def test_update_aws_node_pool_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_node_pool( + aws_service.UpdateAwsNodePoolRequest(), + aws_node_pool=aws_resources.AwsNodePool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_rollback_aws_node_pool_update_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.rollback_aws_node_pool_update in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.rollback_aws_node_pool_update] = mock_rpc + + request = {} + client.rollback_aws_node_pool_update(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.rollback_aws_node_pool_update(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_rollback_aws_node_pool_update_rest_required_fields(request_type=aws_service.RollbackAwsNodePoolUpdateRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_aws_node_pool_update._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()).rollback_aws_node_pool_update._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 = AwsClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.rollback_aws_node_pool_update(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_rollback_aws_node_pool_update_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.rollback_aws_node_pool_update._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_rollback_aws_node_pool_update_rest_flattened(): + client = AwsClustersClient( + 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/awsClusters/sample3/awsNodePools/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.rollback_aws_node_pool_update(**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/*/awsClusters/*/awsNodePools/*}:rollback" % client.transport._host, args[1]) + + +def test_rollback_aws_node_pool_update_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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.rollback_aws_node_pool_update( + aws_service.RollbackAwsNodePoolUpdateRequest(), + name='name_value', + ) + + +def test_get_aws_node_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_aws_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_aws_node_pool] = mock_rpc + + request = {} + client.get_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_aws_node_pool_rest_required_fields(request_type=aws_service.GetAwsNodePoolRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_node_pool._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_aws_node_pool._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 = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = aws_resources.AwsNodePool() + # 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 = aws_resources.AwsNodePool.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_aws_node_pool(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_aws_node_pool_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_aws_node_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_aws_node_pool_rest_flattened(): + client = AwsClustersClient( + 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 = aws_resources.AwsNodePool() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = aws_resources.AwsNodePool.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_aws_node_pool(**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/*/awsClusters/*/awsNodePools/*}" % client.transport._host, args[1]) + + +def test_get_aws_node_pool_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_node_pool( + aws_service.GetAwsNodePoolRequest(), + name='name_value', + ) + + +def test_list_aws_node_pools_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_aws_node_pools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_aws_node_pools] = mock_rpc + + request = {} + client.list_aws_node_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_aws_node_pools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_aws_node_pools_rest_required_fields(request_type=aws_service.ListAwsNodePoolsRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_aws_node_pools._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_aws_node_pools._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + 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 = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = aws_service.ListAwsNodePoolsResponse() + # 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 = aws_service.ListAwsNodePoolsResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_aws_node_pools(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_aws_node_pools_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_aws_node_pools._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_aws_node_pools_rest_flattened(): + client = AwsClustersClient( + 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 = aws_service.ListAwsNodePoolsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/awsClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = aws_service.ListAwsNodePoolsResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_aws_node_pools(**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/*/awsClusters/*}/awsNodePools" % client.transport._host, args[1]) + + +def test_list_aws_node_pools_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_node_pools( + aws_service.ListAwsNodePoolsRequest(), + parent='parent_value', + ) + + +def test_list_aws_node_pools_rest_pager(transport: str = 'rest'): + client = AwsClustersClient( + 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 = ( + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + ], + next_page_token='abc', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[], + next_page_token='def', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + ], + next_page_token='ghi', + ), + aws_service.ListAwsNodePoolsResponse( + aws_node_pools=[ + aws_resources.AwsNodePool(), + aws_resources.AwsNodePool(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(aws_service.ListAwsNodePoolsResponse.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/awsClusters/sample3'} + + pager = client.list_aws_node_pools(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, aws_resources.AwsNodePool) + for i in results) + + pages = list(client.list_aws_node_pools(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_aws_node_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_aws_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_aws_node_pool] = mock_rpc + + request = {} + client.delete_aws_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_aws_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_aws_node_pool_rest_required_fields(request_type=aws_service.DeleteAwsNodePoolRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_aws_node_pool._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_aws_node_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "etag", "ignore_errors", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AwsClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_aws_node_pool(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_aws_node_pool_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_aws_node_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "etag", "ignoreErrors", "validateOnly", )) & set(("name", ))) + + +def test_delete_aws_node_pool_rest_flattened(): + client = AwsClustersClient( + 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/awsClusters/sample3/awsNodePools/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_aws_node_pool(**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/*/awsClusters/*/awsNodePools/*}" % client.transport._host, args[1]) + + +def test_delete_aws_node_pool_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_node_pool( + aws_service.DeleteAwsNodePoolRequest(), + name='name_value', + ) + + +def test_get_aws_open_id_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_aws_open_id_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_aws_open_id_config] = mock_rpc + + request = {} + client.get_aws_open_id_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_aws_open_id_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_aws_open_id_config_rest_required_fields(request_type=aws_service.GetAwsOpenIdConfigRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["aws_cluster"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_open_id_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["awsCluster"] = 'aws_cluster_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_open_id_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "awsCluster" in jsonified_request + assert jsonified_request["awsCluster"] == 'aws_cluster_value' + + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = aws_resources.AwsOpenIdConfig() + # 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 = aws_resources.AwsOpenIdConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_aws_open_id_config(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_aws_open_id_config_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_aws_open_id_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("awsCluster", ))) + + +def test_get_aws_json_web_keys_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_aws_json_web_keys in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_aws_json_web_keys] = mock_rpc + + request = {} + client.get_aws_json_web_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_aws_json_web_keys(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_aws_json_web_keys_rest_required_fields(request_type=aws_service.GetAwsJsonWebKeysRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["aws_cluster"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_json_web_keys._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["awsCluster"] = 'aws_cluster_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_json_web_keys._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "awsCluster" in jsonified_request + assert jsonified_request["awsCluster"] == 'aws_cluster_value' + + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = aws_resources.AwsJsonWebKeys() + # 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 = aws_resources.AwsJsonWebKeys.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_aws_json_web_keys(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_aws_json_web_keys_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_aws_json_web_keys._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("awsCluster", ))) + + +def test_get_aws_server_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_aws_server_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_aws_server_config] = mock_rpc + + request = {} + client.get_aws_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_aws_server_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_aws_server_config_rest_required_fields(request_type=aws_service.GetAwsServerConfigRequest): + transport_class = transports.AwsClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_server_config._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_aws_server_config._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 = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = aws_resources.AwsServerConfig() + # 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 = aws_resources.AwsServerConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_aws_server_config(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_aws_server_config_rest_unset_required_fields(): + transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_aws_server_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_aws_server_config_rest_flattened(): + client = AwsClustersClient( + 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 = aws_resources.AwsServerConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/awsServerConfig'} + + # 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 = aws_resources.AwsServerConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_aws_server_config(**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/*/awsServerConfig}" % client.transport._host, args[1]) + + +def test_get_aws_server_config_rest_flattened_error(transport: str = 'rest'): + client = AwsClustersClient( + 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_aws_server_config( + aws_service.GetAwsServerConfigRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AwsClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AwsClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AwsClustersClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AwsClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AwsClustersClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AwsClustersClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AwsClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AwsClustersClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AwsClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AwsClustersClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AwsClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AwsClustersGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AwsClustersGrpcTransport, + transports.AwsClustersGrpcAsyncIOTransport, + transports.AwsClustersRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = AwsClustersClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_aws_cluster_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.CreateAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_aws_cluster_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.UpdateAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_aws_cluster_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_cluster), + '__call__') as call: + call.return_value = aws_resources.AwsCluster() + client.get_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_aws_clusters_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_clusters), + '__call__') as call: + call.return_value = aws_service.ListAwsClustersResponse() + client.list_aws_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.ListAwsClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_aws_cluster_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.DeleteAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_aws_cluster_agent_token_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_cluster_agent_token), + '__call__') as call: + call.return_value = aws_service.GenerateAwsClusterAgentTokenResponse() + client.generate_aws_cluster_agent_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GenerateAwsClusterAgentTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_aws_access_token_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_access_token), + '__call__') as call: + call.return_value = aws_service.GenerateAwsAccessTokenResponse() + client.generate_aws_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GenerateAwsAccessTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_aws_node_pool_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.CreateAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_aws_node_pool_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.UpdateAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rollback_aws_node_pool_update_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rollback_aws_node_pool_update), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.rollback_aws_node_pool_update(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.RollbackAwsNodePoolUpdateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_aws_node_pool_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_node_pool), + '__call__') as call: + call.return_value = aws_resources.AwsNodePool() + client.get_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_aws_node_pools_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_node_pools), + '__call__') as call: + call.return_value = aws_service.ListAwsNodePoolsResponse() + client.list_aws_node_pools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.ListAwsNodePoolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_aws_node_pool_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.DeleteAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_aws_open_id_config_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_open_id_config), + '__call__') as call: + call.return_value = aws_resources.AwsOpenIdConfig() + client.get_aws_open_id_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsOpenIdConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_aws_json_web_keys_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_json_web_keys), + '__call__') as call: + call.return_value = aws_resources.AwsJsonWebKeys() + client.get_aws_json_web_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsJsonWebKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_aws_server_config_empty_call_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_server_config), + '__call__') as call: + call.return_value = aws_resources.AwsServerConfig() + client.get_aws_server_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsServerConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AwsClustersAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_aws_cluster_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.CreateAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_aws_cluster_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.UpdateAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_aws_cluster_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsCluster( + name='name_value', + description='description_value', + aws_region='aws_region_value', + state=aws_resources.AwsCluster.State.PROVISIONING, + endpoint='endpoint_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + cluster_ca_certificate='cluster_ca_certificate_value', + )) + await client.get_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_aws_clusters_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsClustersResponse( + next_page_token='next_page_token_value', + )) + await client.list_aws_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.ListAwsClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_aws_cluster_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.DeleteAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_aws_cluster_agent_token_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_cluster_agent_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + )) + await client.generate_aws_cluster_agent_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GenerateAwsClusterAgentTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_aws_access_token_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsAccessTokenResponse( + access_token='access_token_value', + )) + await client.generate_aws_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GenerateAwsAccessTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_aws_node_pool_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.CreateAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_aws_node_pool_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.UpdateAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_rollback_aws_node_pool_update_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rollback_aws_node_pool_update), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.rollback_aws_node_pool_update(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.RollbackAwsNodePoolUpdateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_aws_node_pool_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsNodePool( + name='name_value', + version='version_value', + subnet_id='subnet_id_value', + state=aws_resources.AwsNodePool.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + )) + await client.get_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_aws_node_pools_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_node_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsNodePoolsResponse( + next_page_token='next_page_token_value', + )) + await client.list_aws_node_pools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.ListAwsNodePoolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_aws_node_pool_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.DeleteAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_aws_open_id_config_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_open_id_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsOpenIdConfig( + issuer='issuer_value', + jwks_uri='jwks_uri_value', + response_types_supported=['response_types_supported_value'], + subject_types_supported=['subject_types_supported_value'], + id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], + claims_supported=['claims_supported_value'], + grant_types=['grant_types_value'], + )) + await client.get_aws_open_id_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsOpenIdConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_aws_json_web_keys_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_json_web_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsJsonWebKeys( + )) + await client.get_aws_json_web_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsJsonWebKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_aws_server_config_empty_call_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsServerConfig( + name='name_value', + supported_aws_regions=['supported_aws_regions_value'], + )) + await client.get_aws_server_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsServerConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AwsClustersClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_aws_cluster_rest_bad_request(request_type=aws_service.CreateAwsClusterRequest): + client = AwsClustersClient( + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_aws_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.CreateAwsClusterRequest, + dict, +]) +def test_create_aws_cluster_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["aws_cluster"] = {'name': 'name_value', 'description': 'description_value', 'networking': {'vpc_id': 'vpc_id_value', 'pod_address_cidr_blocks': ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'], 'service_address_cidr_blocks': ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'], 'per_node_pool_sg_rules_disabled': True}, 'aws_region': 'aws_region_value', 'control_plane': {'version': 'version_value', 'instance_type': 'instance_type_value', 'ssh_config': {'ec2_key_pair': 'ec2_key_pair_value'}, 'subnet_ids': ['subnet_ids_value1', 'subnet_ids_value2'], 'security_group_ids': ['security_group_ids_value1', 'security_group_ids_value2'], 'iam_instance_profile': 'iam_instance_profile_value', 'root_volume': {'size_gib': 844, 'volume_type': 1, 'iops': 443, 'throughput': 1114, 'kms_key_arn': 'kms_key_arn_value'}, 'main_volume': {}, 'database_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'tags': {}, 'aws_services_authentication': {'role_arn': 'role_arn_value', 'role_session_name': 'role_session_name_value'}, 'proxy_config': {'secret_arn': 'secret_arn_value', 'secret_version': 'secret_version_value'}, 'config_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'instance_placement': {'tenancy': 1}}, 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'state': 1, 'endpoint': 'endpoint_value', 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'cluster_ca_certificate': 'cluster_ca_certificate_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}, 'binary_authorization': {'evaluation_mode': 1}} + # 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 = aws_service.CreateAwsClusterRequest.meta.fields["aws_cluster"] + + 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["aws_cluster"].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["aws_cluster"][field])): + del request_init["aws_cluster"][field][i][subfield] + else: + del request_init["aws_cluster"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_aws_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_aws_cluster_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_create_aws_cluster") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_create_aws_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.CreateAwsClusterRequest.pb(aws_service.CreateAwsClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = aws_service.CreateAwsClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_aws_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_aws_cluster_rest_bad_request(request_type=aws_service.UpdateAwsClusterRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'aws_cluster': {'name': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_aws_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.UpdateAwsClusterRequest, + dict, +]) +def test_update_aws_cluster_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'aws_cluster': {'name': 'projects/sample1/locations/sample2/awsClusters/sample3'}} + request_init["aws_cluster"] = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3', 'description': 'description_value', 'networking': {'vpc_id': 'vpc_id_value', 'pod_address_cidr_blocks': ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'], 'service_address_cidr_blocks': ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'], 'per_node_pool_sg_rules_disabled': True}, 'aws_region': 'aws_region_value', 'control_plane': {'version': 'version_value', 'instance_type': 'instance_type_value', 'ssh_config': {'ec2_key_pair': 'ec2_key_pair_value'}, 'subnet_ids': ['subnet_ids_value1', 'subnet_ids_value2'], 'security_group_ids': ['security_group_ids_value1', 'security_group_ids_value2'], 'iam_instance_profile': 'iam_instance_profile_value', 'root_volume': {'size_gib': 844, 'volume_type': 1, 'iops': 443, 'throughput': 1114, 'kms_key_arn': 'kms_key_arn_value'}, 'main_volume': {}, 'database_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'tags': {}, 'aws_services_authentication': {'role_arn': 'role_arn_value', 'role_session_name': 'role_session_name_value'}, 'proxy_config': {'secret_arn': 'secret_arn_value', 'secret_version': 'secret_version_value'}, 'config_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'instance_placement': {'tenancy': 1}}, 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'state': 1, 'endpoint': 'endpoint_value', 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'cluster_ca_certificate': 'cluster_ca_certificate_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}, 'binary_authorization': {'evaluation_mode': 1}} + # 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 = aws_service.UpdateAwsClusterRequest.meta.fields["aws_cluster"] + + 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["aws_cluster"].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["aws_cluster"][field])): + del request_init["aws_cluster"][field][i][subfield] + else: + del request_init["aws_cluster"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_aws_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_aws_cluster_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_update_aws_cluster") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_update_aws_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.UpdateAwsClusterRequest.pb(aws_service.UpdateAwsClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = aws_service.UpdateAwsClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_aws_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_aws_cluster_rest_bad_request(request_type=aws_service.GetAwsClusterRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_aws_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GetAwsClusterRequest, + dict, +]) +def test_get_aws_cluster_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/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 = aws_resources.AwsCluster( + name='name_value', + description='description_value', + aws_region='aws_region_value', + state=aws_resources.AwsCluster.State.PROVISIONING, + endpoint='endpoint_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + cluster_ca_certificate='cluster_ca_certificate_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = aws_resources.AwsCluster.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_aws_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsCluster) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.aws_region == 'aws_region_value' + assert response.state == aws_resources.AwsCluster.State.PROVISIONING + assert response.endpoint == 'endpoint_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_aws_cluster_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_get_aws_cluster") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_get_aws_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.GetAwsClusterRequest.pb(aws_service.GetAwsClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = aws_resources.AwsCluster.to_json(aws_resources.AwsCluster()) + req.return_value.content = return_value + + request = aws_service.GetAwsClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = aws_resources.AwsCluster() + + client.get_aws_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_aws_clusters_rest_bad_request(request_type=aws_service.ListAwsClustersRequest): + client = AwsClustersClient( + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_aws_clusters(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.ListAwsClustersRequest, + dict, +]) +def test_list_aws_clusters_rest_call_success(request_type): + client = AwsClustersClient( + 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 = aws_service.ListAwsClustersResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = aws_service.ListAwsClustersResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_aws_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAwsClustersPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_aws_clusters_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_list_aws_clusters") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_list_aws_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.ListAwsClustersRequest.pb(aws_service.ListAwsClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = aws_service.ListAwsClustersResponse.to_json(aws_service.ListAwsClustersResponse()) + req.return_value.content = return_value + + request = aws_service.ListAwsClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = aws_service.ListAwsClustersResponse() + + client.list_aws_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_aws_cluster_rest_bad_request(request_type=aws_service.DeleteAwsClusterRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_aws_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.DeleteAwsClusterRequest, + dict, +]) +def test_delete_aws_cluster_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_aws_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_aws_cluster_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_delete_aws_cluster") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_delete_aws_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.DeleteAwsClusterRequest.pb(aws_service.DeleteAwsClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = aws_service.DeleteAwsClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_aws_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_aws_cluster_agent_token_rest_bad_request(request_type=aws_service.GenerateAwsClusterAgentTokenRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.generate_aws_cluster_agent_token(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GenerateAwsClusterAgentTokenRequest, + dict, +]) +def test_generate_aws_cluster_agent_token_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = aws_service.GenerateAwsClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = aws_service.GenerateAwsClusterAgentTokenResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.generate_aws_cluster_agent_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_service.GenerateAwsClusterAgentTokenResponse) + assert response.access_token == 'access_token_value' + assert response.expires_in == 1078 + assert response.token_type == 'token_type_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_aws_cluster_agent_token_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_generate_aws_cluster_agent_token") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_generate_aws_cluster_agent_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.GenerateAwsClusterAgentTokenRequest.pb(aws_service.GenerateAwsClusterAgentTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = aws_service.GenerateAwsClusterAgentTokenResponse.to_json(aws_service.GenerateAwsClusterAgentTokenResponse()) + req.return_value.content = return_value + + request = aws_service.GenerateAwsClusterAgentTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = aws_service.GenerateAwsClusterAgentTokenResponse() + + client.generate_aws_cluster_agent_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_aws_access_token_rest_bad_request(request_type=aws_service.GenerateAwsAccessTokenRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.generate_aws_access_token(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GenerateAwsAccessTokenRequest, + dict, +]) +def test_generate_aws_access_token_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = aws_service.GenerateAwsAccessTokenResponse( + access_token='access_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = aws_service.GenerateAwsAccessTokenResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.generate_aws_access_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_service.GenerateAwsAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_aws_access_token_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_generate_aws_access_token") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_generate_aws_access_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.GenerateAwsAccessTokenRequest.pb(aws_service.GenerateAwsAccessTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = aws_service.GenerateAwsAccessTokenResponse.to_json(aws_service.GenerateAwsAccessTokenResponse()) + req.return_value.content = return_value + + request = aws_service.GenerateAwsAccessTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = aws_service.GenerateAwsAccessTokenResponse() + + client.generate_aws_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_aws_node_pool_rest_bad_request(request_type=aws_service.CreateAwsNodePoolRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_aws_node_pool(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.CreateAwsNodePoolRequest, + dict, +]) +def test_create_aws_node_pool_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/awsClusters/sample3'} + request_init["aws_node_pool"] = {'name': 'name_value', 'version': 'version_value', 'config': {'instance_type': 'instance_type_value', 'root_volume': {'size_gib': 844, 'volume_type': 1, 'iops': 443, 'throughput': 1114, 'kms_key_arn': 'kms_key_arn_value'}, 'taints': [{'key': 'key_value', 'value': 'value_value', 'effect': 1}], 'labels': {}, 'tags': {}, 'iam_instance_profile': 'iam_instance_profile_value', 'image_type': 'image_type_value', 'ssh_config': {'ec2_key_pair': 'ec2_key_pair_value'}, 'security_group_ids': ['security_group_ids_value1', 'security_group_ids_value2'], 'proxy_config': {'secret_arn': 'secret_arn_value', 'secret_version': 'secret_version_value'}, 'config_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'instance_placement': {'tenancy': 1}, 'autoscaling_metrics_collection': {'granularity': 'granularity_value', 'metrics': ['metrics_value1', 'metrics_value2']}, 'spot_config': {'instance_types': ['instance_types_value1', 'instance_types_value2']}}, 'autoscaling': {'min_node_count': 1489, 'max_node_count': 1491}, 'subnet_id': 'subnet_id_value', 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'max_pods_constraint': {'max_pods_per_node': 1798}, 'errors': [{'message': 'message_value'}], 'management': {'auto_repair': True}, 'kubelet_config': {'insecure_kubelet_readonly_port_enabled': True, 'cpu_manager_policy': 'cpu_manager_policy_value', 'cpu_cfs_quota': True, 'cpu_cfs_quota_period': 'cpu_cfs_quota_period_value', 'pod_pids_limit': 1488}, 'update_settings': {'surge_settings': {'max_surge': 971, 'max_unavailable': 1577}}} + # 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 = aws_service.CreateAwsNodePoolRequest.meta.fields["aws_node_pool"] + + 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["aws_node_pool"].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["aws_node_pool"][field])): + del request_init["aws_node_pool"][field][i][subfield] + else: + del request_init["aws_node_pool"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_aws_node_pool(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_aws_node_pool_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_create_aws_node_pool") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_create_aws_node_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.CreateAwsNodePoolRequest.pb(aws_service.CreateAwsNodePoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = aws_service.CreateAwsNodePoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_aws_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_aws_node_pool_rest_bad_request(request_type=aws_service.UpdateAwsNodePoolRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'aws_node_pool': {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_aws_node_pool(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.UpdateAwsNodePoolRequest, + dict, +]) +def test_update_aws_node_pool_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'aws_node_pool': {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'}} + request_init["aws_node_pool"] = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4', 'version': 'version_value', 'config': {'instance_type': 'instance_type_value', 'root_volume': {'size_gib': 844, 'volume_type': 1, 'iops': 443, 'throughput': 1114, 'kms_key_arn': 'kms_key_arn_value'}, 'taints': [{'key': 'key_value', 'value': 'value_value', 'effect': 1}], 'labels': {}, 'tags': {}, 'iam_instance_profile': 'iam_instance_profile_value', 'image_type': 'image_type_value', 'ssh_config': {'ec2_key_pair': 'ec2_key_pair_value'}, 'security_group_ids': ['security_group_ids_value1', 'security_group_ids_value2'], 'proxy_config': {'secret_arn': 'secret_arn_value', 'secret_version': 'secret_version_value'}, 'config_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'instance_placement': {'tenancy': 1}, 'autoscaling_metrics_collection': {'granularity': 'granularity_value', 'metrics': ['metrics_value1', 'metrics_value2']}, 'spot_config': {'instance_types': ['instance_types_value1', 'instance_types_value2']}}, 'autoscaling': {'min_node_count': 1489, 'max_node_count': 1491}, 'subnet_id': 'subnet_id_value', 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'max_pods_constraint': {'max_pods_per_node': 1798}, 'errors': [{'message': 'message_value'}], 'management': {'auto_repair': True}, 'kubelet_config': {'insecure_kubelet_readonly_port_enabled': True, 'cpu_manager_policy': 'cpu_manager_policy_value', 'cpu_cfs_quota': True, 'cpu_cfs_quota_period': 'cpu_cfs_quota_period_value', 'pod_pids_limit': 1488}, 'update_settings': {'surge_settings': {'max_surge': 971, 'max_unavailable': 1577}}} + # 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 = aws_service.UpdateAwsNodePoolRequest.meta.fields["aws_node_pool"] + + 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["aws_node_pool"].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["aws_node_pool"][field])): + del request_init["aws_node_pool"][field][i][subfield] + else: + del request_init["aws_node_pool"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_aws_node_pool(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_aws_node_pool_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_update_aws_node_pool") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_update_aws_node_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.UpdateAwsNodePoolRequest.pb(aws_service.UpdateAwsNodePoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = aws_service.UpdateAwsNodePoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_aws_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_rollback_aws_node_pool_update_rest_bad_request(request_type=aws_service.RollbackAwsNodePoolUpdateRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.rollback_aws_node_pool_update(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.RollbackAwsNodePoolUpdateRequest, + dict, +]) +def test_rollback_aws_node_pool_update_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.rollback_aws_node_pool_update(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_rollback_aws_node_pool_update_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_rollback_aws_node_pool_update") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_rollback_aws_node_pool_update") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.RollbackAwsNodePoolUpdateRequest.pb(aws_service.RollbackAwsNodePoolUpdateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = aws_service.RollbackAwsNodePoolUpdateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.rollback_aws_node_pool_update(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_aws_node_pool_rest_bad_request(request_type=aws_service.GetAwsNodePoolRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_aws_node_pool(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GetAwsNodePoolRequest, + dict, +]) +def test_get_aws_node_pool_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = aws_resources.AwsNodePool( + name='name_value', + version='version_value', + subnet_id='subnet_id_value', + state=aws_resources.AwsNodePool.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = aws_resources.AwsNodePool.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_aws_node_pool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsNodePool) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.subnet_id == 'subnet_id_value' + assert response.state == aws_resources.AwsNodePool.State.PROVISIONING + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_aws_node_pool_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_get_aws_node_pool") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_get_aws_node_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.GetAwsNodePoolRequest.pb(aws_service.GetAwsNodePoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = aws_resources.AwsNodePool.to_json(aws_resources.AwsNodePool()) + req.return_value.content = return_value + + request = aws_service.GetAwsNodePoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = aws_resources.AwsNodePool() + + client.get_aws_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_aws_node_pools_rest_bad_request(request_type=aws_service.ListAwsNodePoolsRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_aws_node_pools(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.ListAwsNodePoolsRequest, + dict, +]) +def test_list_aws_node_pools_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/awsClusters/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 = aws_service.ListAwsNodePoolsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = aws_service.ListAwsNodePoolsResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_aws_node_pools(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAwsNodePoolsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_aws_node_pools_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_list_aws_node_pools") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_list_aws_node_pools") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.ListAwsNodePoolsRequest.pb(aws_service.ListAwsNodePoolsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = aws_service.ListAwsNodePoolsResponse.to_json(aws_service.ListAwsNodePoolsResponse()) + req.return_value.content = return_value + + request = aws_service.ListAwsNodePoolsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = aws_service.ListAwsNodePoolsResponse() + + client.list_aws_node_pools(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_aws_node_pool_rest_bad_request(request_type=aws_service.DeleteAwsNodePoolRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_aws_node_pool(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.DeleteAwsNodePoolRequest, + dict, +]) +def test_delete_aws_node_pool_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_aws_node_pool(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_aws_node_pool_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_delete_aws_node_pool") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_delete_aws_node_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.DeleteAwsNodePoolRequest.pb(aws_service.DeleteAwsNodePoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = aws_service.DeleteAwsNodePoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_aws_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_aws_open_id_config_rest_bad_request(request_type=aws_service.GetAwsOpenIdConfigRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_aws_open_id_config(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GetAwsOpenIdConfigRequest, + dict, +]) +def test_get_aws_open_id_config_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = aws_resources.AwsOpenIdConfig( + issuer='issuer_value', + jwks_uri='jwks_uri_value', + response_types_supported=['response_types_supported_value'], + subject_types_supported=['subject_types_supported_value'], + id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], + claims_supported=['claims_supported_value'], + grant_types=['grant_types_value'], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = aws_resources.AwsOpenIdConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_aws_open_id_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsOpenIdConfig) + assert response.issuer == 'issuer_value' + assert response.jwks_uri == 'jwks_uri_value' + assert response.response_types_supported == ['response_types_supported_value'] + assert response.subject_types_supported == ['subject_types_supported_value'] + assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] + assert response.claims_supported == ['claims_supported_value'] + assert response.grant_types == ['grant_types_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_aws_open_id_config_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_get_aws_open_id_config") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_get_aws_open_id_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.GetAwsOpenIdConfigRequest.pb(aws_service.GetAwsOpenIdConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = aws_resources.AwsOpenIdConfig.to_json(aws_resources.AwsOpenIdConfig()) + req.return_value.content = return_value + + request = aws_service.GetAwsOpenIdConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = aws_resources.AwsOpenIdConfig() + + client.get_aws_open_id_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_aws_json_web_keys_rest_bad_request(request_type=aws_service.GetAwsJsonWebKeysRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_aws_json_web_keys(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GetAwsJsonWebKeysRequest, + dict, +]) +def test_get_aws_json_web_keys_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = aws_resources.AwsJsonWebKeys( + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = aws_resources.AwsJsonWebKeys.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_aws_json_web_keys(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsJsonWebKeys) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_aws_json_web_keys_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_get_aws_json_web_keys") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_get_aws_json_web_keys") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.GetAwsJsonWebKeysRequest.pb(aws_service.GetAwsJsonWebKeysRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = aws_resources.AwsJsonWebKeys.to_json(aws_resources.AwsJsonWebKeys()) + req.return_value.content = return_value + + request = aws_service.GetAwsJsonWebKeysRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = aws_resources.AwsJsonWebKeys() + + client.get_aws_json_web_keys(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_aws_server_config_rest_bad_request(request_type=aws_service.GetAwsServerConfigRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsServerConfig'} + 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_aws_server_config(request) + + +@pytest.mark.parametrize("request_type", [ + aws_service.GetAwsServerConfigRequest, + dict, +]) +def test_get_aws_server_config_rest_call_success(request_type): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/awsServerConfig'} + 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 = aws_resources.AwsServerConfig( + name='name_value', + supported_aws_regions=['supported_aws_regions_value'], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = aws_resources.AwsServerConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_aws_server_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, aws_resources.AwsServerConfig) + assert response.name == 'name_value' + assert response.supported_aws_regions == ['supported_aws_regions_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_aws_server_config_rest_interceptors(null_interceptor): + transport = transports.AwsClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), + ) + client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_get_aws_server_config") as post, \ + mock.patch.object(transports.AwsClustersRestInterceptor, "pre_get_aws_server_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = aws_service.GetAwsServerConfigRequest.pb(aws_service.GetAwsServerConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = aws_resources.AwsServerConfig.to_json(aws_resources.AwsServerConfig()) + req.return_value.content = return_value + + request = aws_service.GetAwsServerConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = aws_resources.AwsServerConfig() + + client.get_aws_server_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = AwsClustersClient( + 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(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 = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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(request_type=operations_pb2.DeleteOperationRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = AwsClustersClient( + 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(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 = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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(request_type=operations_pb2.GetOperationRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = AwsClustersClient( + 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(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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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(request_type=operations_pb2.ListOperationsRequest): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = AwsClustersClient( + 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(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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_initialize_client_w_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_aws_cluster_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_cluster), + '__call__') as call: + client.create_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.CreateAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_aws_cluster_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_cluster), + '__call__') as call: + client.update_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.UpdateAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_aws_cluster_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_cluster), + '__call__') as call: + client.get_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_aws_clusters_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_clusters), + '__call__') as call: + client.list_aws_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.ListAwsClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_aws_cluster_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_cluster), + '__call__') as call: + client.delete_aws_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.DeleteAwsClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_aws_cluster_agent_token_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_cluster_agent_token), + '__call__') as call: + client.generate_aws_cluster_agent_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GenerateAwsClusterAgentTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_aws_access_token_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_aws_access_token), + '__call__') as call: + client.generate_aws_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GenerateAwsAccessTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_aws_node_pool_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_aws_node_pool), + '__call__') as call: + client.create_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.CreateAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_aws_node_pool_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_aws_node_pool), + '__call__') as call: + client.update_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.UpdateAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rollback_aws_node_pool_update_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rollback_aws_node_pool_update), + '__call__') as call: + client.rollback_aws_node_pool_update(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.RollbackAwsNodePoolUpdateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_aws_node_pool_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_node_pool), + '__call__') as call: + client.get_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_aws_node_pools_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_aws_node_pools), + '__call__') as call: + client.list_aws_node_pools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.ListAwsNodePoolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_aws_node_pool_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_aws_node_pool), + '__call__') as call: + client.delete_aws_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.DeleteAwsNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_aws_open_id_config_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_open_id_config), + '__call__') as call: + client.get_aws_open_id_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsOpenIdConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_aws_json_web_keys_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_json_web_keys), + '__call__') as call: + client.get_aws_json_web_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsJsonWebKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_aws_server_config_empty_call_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_aws_server_config), + '__call__') as call: + client.get_aws_server_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = aws_service.GetAwsServerConfigRequest() + + assert args[0] == request_msg + + +def test_aws_clusters_rest_lro_client(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an 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 + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AwsClustersGrpcTransport, + ) + +def test_aws_clusters_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AwsClustersTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_aws_clusters_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.gke_multicloud_v1.services.aws_clusters.transports.AwsClustersTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AwsClustersTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_aws_cluster', + 'update_aws_cluster', + 'get_aws_cluster', + 'list_aws_clusters', + 'delete_aws_cluster', + 'generate_aws_cluster_agent_token', + 'generate_aws_access_token', + 'create_aws_node_pool', + 'update_aws_node_pool', + 'rollback_aws_node_pool_update', + 'get_aws_node_pool', + 'list_aws_node_pools', + 'delete_aws_node_pool', + 'get_aws_open_id_config', + 'get_aws_json_web_keys', + 'get_aws_server_config', + '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_aws_clusters_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.gke_multicloud_v1.services.aws_clusters.transports.AwsClustersTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AwsClustersTransport( + 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_aws_clusters_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.gke_multicloud_v1.services.aws_clusters.transports.AwsClustersTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AwsClustersTransport() + adc.assert_called_once() + + +def test_aws_clusters_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) + AwsClustersClient() + 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.AwsClustersGrpcTransport, + transports.AwsClustersGrpcAsyncIOTransport, + ], +) +def test_aws_clusters_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.AwsClustersGrpcTransport, + transports.AwsClustersGrpcAsyncIOTransport, + transports.AwsClustersRestTransport, + ], +) +def test_aws_clusters_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.AwsClustersGrpcTransport, grpc_helpers), + (transports.AwsClustersGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_aws_clusters_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( + "gkemulticloud.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="gkemulticloud.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AwsClustersGrpcTransport, transports.AwsClustersGrpcAsyncIOTransport]) +def test_aws_clusters_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_aws_clusters_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.AwsClustersRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_aws_clusters_host_no_port(transport_name): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'gkemulticloud.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://gkemulticloud.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_aws_clusters_host_with_port(transport_name): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'gkemulticloud.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://gkemulticloud.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_aws_clusters_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AwsClustersClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AwsClustersClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_aws_cluster._session + session2 = client2.transport.create_aws_cluster._session + assert session1 != session2 + session1 = client1.transport.update_aws_cluster._session + session2 = client2.transport.update_aws_cluster._session + assert session1 != session2 + session1 = client1.transport.get_aws_cluster._session + session2 = client2.transport.get_aws_cluster._session + assert session1 != session2 + session1 = client1.transport.list_aws_clusters._session + session2 = client2.transport.list_aws_clusters._session + assert session1 != session2 + session1 = client1.transport.delete_aws_cluster._session + session2 = client2.transport.delete_aws_cluster._session + assert session1 != session2 + session1 = client1.transport.generate_aws_cluster_agent_token._session + session2 = client2.transport.generate_aws_cluster_agent_token._session + assert session1 != session2 + session1 = client1.transport.generate_aws_access_token._session + session2 = client2.transport.generate_aws_access_token._session + assert session1 != session2 + session1 = client1.transport.create_aws_node_pool._session + session2 = client2.transport.create_aws_node_pool._session + assert session1 != session2 + session1 = client1.transport.update_aws_node_pool._session + session2 = client2.transport.update_aws_node_pool._session + assert session1 != session2 + session1 = client1.transport.rollback_aws_node_pool_update._session + session2 = client2.transport.rollback_aws_node_pool_update._session + assert session1 != session2 + session1 = client1.transport.get_aws_node_pool._session + session2 = client2.transport.get_aws_node_pool._session + assert session1 != session2 + session1 = client1.transport.list_aws_node_pools._session + session2 = client2.transport.list_aws_node_pools._session + assert session1 != session2 + session1 = client1.transport.delete_aws_node_pool._session + session2 = client2.transport.delete_aws_node_pool._session + assert session1 != session2 + session1 = client1.transport.get_aws_open_id_config._session + session2 = client2.transport.get_aws_open_id_config._session + assert session1 != session2 + session1 = client1.transport.get_aws_json_web_keys._session + session2 = client2.transport.get_aws_json_web_keys._session + assert session1 != session2 + session1 = client1.transport.get_aws_server_config._session + session2 = client2.transport.get_aws_server_config._session + assert session1 != session2 +def test_aws_clusters_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AwsClustersGrpcTransport( + 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_aws_clusters_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AwsClustersGrpcAsyncIOTransport( + 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.AwsClustersGrpcTransport, transports.AwsClustersGrpcAsyncIOTransport]) +def test_aws_clusters_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.AwsClustersGrpcTransport, transports.AwsClustersGrpcAsyncIOTransport]) +def test_aws_clusters_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_aws_clusters_grpc_lro_client(): + client = AwsClustersClient( + 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_aws_clusters_grpc_lro_async_client(): + client = AwsClustersAsyncClient( + 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_aws_cluster_path(): + project = "squid" + location = "clam" + aws_cluster = "whelk" + expected = "projects/{project}/locations/{location}/awsClusters/{aws_cluster}".format(project=project, location=location, aws_cluster=aws_cluster, ) + actual = AwsClustersClient.aws_cluster_path(project, location, aws_cluster) + assert expected == actual + + +def test_parse_aws_cluster_path(): + expected = { + "project": "octopus", + "location": "oyster", + "aws_cluster": "nudibranch", + } + path = AwsClustersClient.aws_cluster_path(**expected) + + # Check that the path construction is reversible. + actual = AwsClustersClient.parse_aws_cluster_path(path) + assert expected == actual + +def test_aws_node_pool_path(): + project = "cuttlefish" + location = "mussel" + aws_cluster = "winkle" + aws_node_pool = "nautilus" + expected = "projects/{project}/locations/{location}/awsClusters/{aws_cluster}/awsNodePools/{aws_node_pool}".format(project=project, location=location, aws_cluster=aws_cluster, aws_node_pool=aws_node_pool, ) + actual = AwsClustersClient.aws_node_pool_path(project, location, aws_cluster, aws_node_pool) + assert expected == actual + + +def test_parse_aws_node_pool_path(): + expected = { + "project": "scallop", + "location": "abalone", + "aws_cluster": "squid", + "aws_node_pool": "clam", + } + path = AwsClustersClient.aws_node_pool_path(**expected) + + # Check that the path construction is reversible. + actual = AwsClustersClient.parse_aws_node_pool_path(path) + assert expected == actual + +def test_aws_server_config_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}/awsServerConfig".format(project=project, location=location, ) + actual = AwsClustersClient.aws_server_config_path(project, location) + assert expected == actual + + +def test_parse_aws_server_config_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = AwsClustersClient.aws_server_config_path(**expected) + + # Check that the path construction is reversible. + actual = AwsClustersClient.parse_aws_server_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AwsClustersClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = AwsClustersClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AwsClustersClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = AwsClustersClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = AwsClustersClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AwsClustersClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AwsClustersClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = AwsClustersClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AwsClustersClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = AwsClustersClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = AwsClustersClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AwsClustersClient.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 = AwsClustersClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = AwsClustersClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AwsClustersClient.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.AwsClustersTransport, '_prep_wrapped_messages') as prep: + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AwsClustersTransport, '_prep_wrapped_messages') as prep: + transport_class = AwsClustersClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = AwsClustersClient( + 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_asyncio"): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AwsClustersClient( + 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 = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AwsClustersClient( + 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 = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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 = AwsClustersClient( + 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_asyncio"): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AwsClustersClient( + 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 = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AwsClustersClient( + 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 = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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 = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AwsClustersClient( + 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 = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AwsClustersClient( + 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 = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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 = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AwsClustersClient( + 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 = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AwsClustersClient( + 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 = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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_transport_close_grpc(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AwsClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_rest(): + client = AwsClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "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 = AwsClustersClient( + 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", [ + (AwsClustersClient, transports.AwsClustersGrpcTransport), + (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_azure_clusters.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_azure_clusters.py new file mode 100644 index 000000000000..bb38ff4336ea --- /dev/null +++ b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_azure_clusters.py @@ -0,0 +1,15936 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.gke_multicloud_v1.services.azure_clusters import AzureClustersAsyncClient +from google.cloud.gke_multicloud_v1.services.azure_clusters import AzureClustersClient +from google.cloud.gke_multicloud_v1.services.azure_clusters import pagers +from google.cloud.gke_multicloud_v1.services.azure_clusters import transports +from google.cloud.gke_multicloud_v1.types import azure_resources +from google.cloud.gke_multicloud_v1.types import azure_service +from google.cloud.gke_multicloud_v1.types import common_resources +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 + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AzureClustersClient._get_default_mtls_endpoint(None) is None + assert AzureClustersClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AzureClustersClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AzureClustersClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AzureClustersClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AzureClustersClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AzureClustersClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AzureClustersClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AzureClustersClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AzureClustersClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert AzureClustersClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AzureClustersClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AzureClustersClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AzureClustersClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert AzureClustersClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert AzureClustersClient._get_client_cert_source(None, False) is None + assert AzureClustersClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AzureClustersClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert AzureClustersClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AzureClustersClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AzureClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersClient)) +@mock.patch.object(AzureClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AzureClustersClient._DEFAULT_UNIVERSE + default_endpoint = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AzureClustersClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AzureClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AzureClustersClient.DEFAULT_MTLS_ENDPOINT + assert AzureClustersClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AzureClustersClient._get_api_endpoint(None, None, default_universe, "always") == AzureClustersClient.DEFAULT_MTLS_ENDPOINT + assert AzureClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AzureClustersClient.DEFAULT_MTLS_ENDPOINT + assert AzureClustersClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AzureClustersClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AzureClustersClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert AzureClustersClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AzureClustersClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AzureClustersClient._get_universe_domain(None, None) == AzureClustersClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AzureClustersClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AzureClustersClient, "grpc"), + (AzureClustersAsyncClient, "grpc_asyncio"), + (AzureClustersClient, "rest"), +]) +def test_azure_clusters_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 == ( + 'gkemulticloud.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://gkemulticloud.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AzureClustersGrpcTransport, "grpc"), + (transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AzureClustersRestTransport, "rest"), +]) +def test_azure_clusters_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", [ + (AzureClustersClient, "grpc"), + (AzureClustersAsyncClient, "grpc_asyncio"), + (AzureClustersClient, "rest"), +]) +def test_azure_clusters_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 == ( + 'gkemulticloud.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://gkemulticloud.googleapis.com' + ) + + +def test_azure_clusters_client_get_transport_class(): + transport = AzureClustersClient.get_transport_class() + available_transports = [ + transports.AzureClustersGrpcTransport, + transports.AzureClustersRestTransport, + ] + assert transport in available_transports + + transport = AzureClustersClient.get_transport_class("grpc") + assert transport == transports.AzureClustersGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc"), + (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio"), + (AzureClustersClient, transports.AzureClustersRestTransport, "rest"), +]) +@mock.patch.object(AzureClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersClient)) +@mock.patch.object(AzureClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersAsyncClient)) +def test_azure_clusters_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(AzureClustersClient, '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(AzureClustersClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc", "true"), + (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc", "false"), + (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AzureClustersClient, transports.AzureClustersRestTransport, "rest", "true"), + (AzureClustersClient, transports.AzureClustersRestTransport, "rest", "false"), +]) +@mock.patch.object(AzureClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersClient)) +@mock.patch.object(AzureClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_azure_clusters_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + AzureClustersClient, AzureClustersAsyncClient +]) +@mock.patch.object(AzureClustersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AzureClustersClient)) +@mock.patch.object(AzureClustersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AzureClustersAsyncClient)) +def test_azure_clusters_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + AzureClustersClient, AzureClustersAsyncClient +]) +@mock.patch.object(AzureClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersClient)) +@mock.patch.object(AzureClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersAsyncClient)) +def test_azure_clusters_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AzureClustersClient._DEFAULT_UNIVERSE + default_endpoint = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc"), + (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio"), + (AzureClustersClient, transports.AzureClustersRestTransport, "rest"), +]) +def test_azure_clusters_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc", grpc_helpers), + (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AzureClustersClient, transports.AzureClustersRestTransport, "rest", None), +]) +def test_azure_clusters_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_azure_clusters_client_client_options_from_dict(): + with mock.patch('google.cloud.gke_multicloud_v1.services.azure_clusters.transports.AzureClustersGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AzureClustersClient( + 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", [ + (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc", grpc_helpers), + (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_azure_clusters_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "gkemulticloud.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="gkemulticloud.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.CreateAzureClientRequest, + dict, +]) +def test_create_azure_client(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_client), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.CreateAzureClientRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_azure_client_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.CreateAzureClientRequest( + parent='parent_value', + azure_client_id='azure_client_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_client), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_azure_client(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.CreateAzureClientRequest( + parent='parent_value', + azure_client_id='azure_client_id_value', + ) + +def test_create_azure_client_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_azure_client in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_azure_client] = mock_rpc + request = {} + client.create_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_azure_client(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_azure_client_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_azure_client in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_azure_client] = mock_rpc + + request = {} + await client.create_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_azure_client(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_azure_client_async(transport: str = 'grpc_asyncio', request_type=azure_service.CreateAzureClientRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_client), + '__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_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.CreateAzureClientRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_azure_client_async_from_dict(): + await test_create_azure_client_async(request_type=dict) + +def test_create_azure_client_field_headers(): + client = AzureClustersClient( + 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 = azure_service.CreateAzureClientRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_client), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_azure_client(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_azure_client_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.CreateAzureClientRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_client), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_azure_client(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_azure_client_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_client), + '__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_azure_client( + parent='parent_value', + azure_client=azure_resources.AzureClient(name='name_value'), + azure_client_id='azure_client_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].azure_client + mock_val = azure_resources.AzureClient(name='name_value') + assert arg == mock_val + arg = args[0].azure_client_id + mock_val = 'azure_client_id_value' + assert arg == mock_val + + +def test_create_azure_client_flattened_error(): + client = AzureClustersClient( + 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_azure_client( + azure_service.CreateAzureClientRequest(), + parent='parent_value', + azure_client=azure_resources.AzureClient(name='name_value'), + azure_client_id='azure_client_id_value', + ) + +@pytest.mark.asyncio +async def test_create_azure_client_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_client), + '__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_azure_client( + parent='parent_value', + azure_client=azure_resources.AzureClient(name='name_value'), + azure_client_id='azure_client_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].azure_client + mock_val = azure_resources.AzureClient(name='name_value') + assert arg == mock_val + arg = args[0].azure_client_id + mock_val = 'azure_client_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_azure_client_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_azure_client( + azure_service.CreateAzureClientRequest(), + parent='parent_value', + azure_client=azure_resources.AzureClient(name='name_value'), + azure_client_id='azure_client_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureClientRequest, + dict, +]) +def test_get_azure_client(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_client), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureClient( + name='name_value', + tenant_id='tenant_id_value', + application_id='application_id_value', + reconciling=True, + pem_certificate='pem_certificate_value', + uid='uid_value', + ) + response = client.get_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureClientRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureClient) + assert response.name == 'name_value' + assert response.tenant_id == 'tenant_id_value' + assert response.application_id == 'application_id_value' + assert response.reconciling is True + assert response.pem_certificate == 'pem_certificate_value' + assert response.uid == 'uid_value' + + +def test_get_azure_client_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.GetAzureClientRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_client), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_azure_client(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.GetAzureClientRequest( + name='name_value', + ) + +def test_get_azure_client_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_client in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_client] = mock_rpc + request = {} + client.get_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_client(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_client_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_azure_client in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_azure_client] = mock_rpc + + request = {} + await client.get_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_azure_client(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_client_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureClientRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_client), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureClient( + name='name_value', + tenant_id='tenant_id_value', + application_id='application_id_value', + reconciling=True, + pem_certificate='pem_certificate_value', + uid='uid_value', + )) + response = await client.get_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureClientRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureClient) + assert response.name == 'name_value' + assert response.tenant_id == 'tenant_id_value' + assert response.application_id == 'application_id_value' + assert response.reconciling is True + assert response.pem_certificate == 'pem_certificate_value' + assert response.uid == 'uid_value' + + +@pytest.mark.asyncio +async def test_get_azure_client_async_from_dict(): + await test_get_azure_client_async(request_type=dict) + +def test_get_azure_client_field_headers(): + client = AzureClustersClient( + 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 = azure_service.GetAzureClientRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_client), + '__call__') as call: + call.return_value = azure_resources.AzureClient() + client.get_azure_client(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_azure_client_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.GetAzureClientRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_client), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureClient()) + await client.get_azure_client(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_azure_client_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_client), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureClient() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_azure_client( + 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_azure_client_flattened_error(): + client = AzureClustersClient( + 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_azure_client( + azure_service.GetAzureClientRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_azure_client_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_client), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureClient() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureClient()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_azure_client( + 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_azure_client_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_azure_client( + azure_service.GetAzureClientRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.ListAzureClientsRequest, + dict, +]) +def test_list_azure_clients(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_clients), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.ListAzureClientsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_azure_clients(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.ListAzureClientsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAzureClientsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_azure_clients_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.ListAzureClientsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clients), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_azure_clients(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.ListAzureClientsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_azure_clients_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_azure_clients in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_azure_clients] = mock_rpc + request = {} + client.list_azure_clients(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_azure_clients(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_azure_clients_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_azure_clients in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_azure_clients] = mock_rpc + + request = {} + await client.list_azure_clients(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_azure_clients(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_azure_clients_async(transport: str = 'grpc_asyncio', request_type=azure_service.ListAzureClientsRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_clients), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClientsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_azure_clients(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.ListAzureClientsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAzureClientsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_azure_clients_async_from_dict(): + await test_list_azure_clients_async(request_type=dict) + +def test_list_azure_clients_field_headers(): + client = AzureClustersClient( + 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 = azure_service.ListAzureClientsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clients), + '__call__') as call: + call.return_value = azure_service.ListAzureClientsResponse() + client.list_azure_clients(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_azure_clients_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.ListAzureClientsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clients), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClientsResponse()) + await client.list_azure_clients(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_azure_clients_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clients), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.ListAzureClientsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_azure_clients( + 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_azure_clients_flattened_error(): + client = AzureClustersClient( + 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_azure_clients( + azure_service.ListAzureClientsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_azure_clients_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clients), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.ListAzureClientsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClientsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_azure_clients( + 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_azure_clients_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_azure_clients( + azure_service.ListAzureClientsRequest(), + parent='parent_value', + ) + + +def test_list_azure_clients_pager(transport_name: str = "grpc"): + client = AzureClustersClient( + 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_azure_clients), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + azure_resources.AzureClient(), + azure_resources.AzureClient(), + ], + next_page_token='abc', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[], + next_page_token='def', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + azure_resources.AzureClient(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_azure_clients(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, azure_resources.AzureClient) + for i in results) +def test_list_azure_clients_pages(transport_name: str = "grpc"): + client = AzureClustersClient( + 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_azure_clients), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + azure_resources.AzureClient(), + azure_resources.AzureClient(), + ], + next_page_token='abc', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[], + next_page_token='def', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + azure_resources.AzureClient(), + ], + ), + RuntimeError, + ) + pages = list(client.list_azure_clients(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_azure_clients_async_pager(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clients), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + azure_resources.AzureClient(), + azure_resources.AzureClient(), + ], + next_page_token='abc', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[], + next_page_token='def', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + azure_resources.AzureClient(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_azure_clients(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, azure_resources.AzureClient) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_azure_clients_async_pages(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clients), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + azure_resources.AzureClient(), + azure_resources.AzureClient(), + ], + next_page_token='abc', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[], + next_page_token='def', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + azure_resources.AzureClient(), + ], + ), + 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_azure_clients(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", [ + azure_service.DeleteAzureClientRequest, + dict, +]) +def test_delete_azure_client(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_client), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.DeleteAzureClientRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_azure_client_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.DeleteAzureClientRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_client), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_azure_client(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.DeleteAzureClientRequest( + name='name_value', + ) + +def test_delete_azure_client_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_azure_client in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_azure_client] = mock_rpc + request = {} + client.delete_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_azure_client(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_azure_client_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_azure_client in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_azure_client] = mock_rpc + + request = {} + await client.delete_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_azure_client(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_azure_client_async(transport: str = 'grpc_asyncio', request_type=azure_service.DeleteAzureClientRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_client), + '__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_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.DeleteAzureClientRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_azure_client_async_from_dict(): + await test_delete_azure_client_async(request_type=dict) + +def test_delete_azure_client_field_headers(): + client = AzureClustersClient( + 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 = azure_service.DeleteAzureClientRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_client), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_azure_client(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_azure_client_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.DeleteAzureClientRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_client), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_azure_client(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_azure_client_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_client), + '__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_azure_client( + 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_azure_client_flattened_error(): + client = AzureClustersClient( + 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_azure_client( + azure_service.DeleteAzureClientRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_azure_client_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_client), + '__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_azure_client( + 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_azure_client_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_azure_client( + azure_service.DeleteAzureClientRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.CreateAzureClusterRequest, + dict, +]) +def test_create_azure_cluster(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.CreateAzureClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_azure_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.CreateAzureClusterRequest( + parent='parent_value', + azure_cluster_id='azure_cluster_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_azure_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.CreateAzureClusterRequest( + parent='parent_value', + azure_cluster_id='azure_cluster_id_value', + ) + +def test_create_azure_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_azure_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_azure_cluster] = mock_rpc + request = {} + client.create_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_azure_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_azure_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_azure_cluster] = mock_rpc + + request = {} + await client.create_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_azure_cluster_async(transport: str = 'grpc_asyncio', request_type=azure_service.CreateAzureClusterRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_cluster), + '__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_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.CreateAzureClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_azure_cluster_async_from_dict(): + await test_create_azure_cluster_async(request_type=dict) + +def test_create_azure_cluster_field_headers(): + client = AzureClustersClient( + 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 = azure_service.CreateAzureClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_azure_cluster(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_azure_cluster_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.CreateAzureClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_azure_cluster(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_azure_cluster_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_cluster), + '__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_azure_cluster( + parent='parent_value', + azure_cluster=azure_resources.AzureCluster(name='name_value'), + azure_cluster_id='azure_cluster_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].azure_cluster + mock_val = azure_resources.AzureCluster(name='name_value') + assert arg == mock_val + arg = args[0].azure_cluster_id + mock_val = 'azure_cluster_id_value' + assert arg == mock_val + + +def test_create_azure_cluster_flattened_error(): + client = AzureClustersClient( + 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_azure_cluster( + azure_service.CreateAzureClusterRequest(), + parent='parent_value', + azure_cluster=azure_resources.AzureCluster(name='name_value'), + azure_cluster_id='azure_cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_azure_cluster_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_cluster), + '__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_azure_cluster( + parent='parent_value', + azure_cluster=azure_resources.AzureCluster(name='name_value'), + azure_cluster_id='azure_cluster_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].azure_cluster + mock_val = azure_resources.AzureCluster(name='name_value') + assert arg == mock_val + arg = args[0].azure_cluster_id + mock_val = 'azure_cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_azure_cluster_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_azure_cluster( + azure_service.CreateAzureClusterRequest(), + parent='parent_value', + azure_cluster=azure_resources.AzureCluster(name='name_value'), + azure_cluster_id='azure_cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.UpdateAzureClusterRequest, + dict, +]) +def test_update_azure_cluster(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.UpdateAzureClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_azure_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.UpdateAzureClusterRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_azure_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.UpdateAzureClusterRequest( + ) + +def test_update_azure_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_azure_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_azure_cluster] = mock_rpc + request = {} + client.update_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_azure_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_azure_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_azure_cluster] = mock_rpc + + request = {} + await client.update_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_azure_cluster_async(transport: str = 'grpc_asyncio', request_type=azure_service.UpdateAzureClusterRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_cluster), + '__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_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.UpdateAzureClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_azure_cluster_async_from_dict(): + await test_update_azure_cluster_async(request_type=dict) + +def test_update_azure_cluster_field_headers(): + client = AzureClustersClient( + 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 = azure_service.UpdateAzureClusterRequest() + + request.azure_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_azure_cluster(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', + 'azure_cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_azure_cluster_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.UpdateAzureClusterRequest() + + request.azure_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_azure_cluster(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', + 'azure_cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_azure_cluster_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_cluster), + '__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_azure_cluster( + azure_cluster=azure_resources.AzureCluster(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].azure_cluster + mock_val = azure_resources.AzureCluster(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_azure_cluster_flattened_error(): + client = AzureClustersClient( + 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_azure_cluster( + azure_service.UpdateAzureClusterRequest(), + azure_cluster=azure_resources.AzureCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_azure_cluster_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_cluster), + '__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_azure_cluster( + azure_cluster=azure_resources.AzureCluster(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].azure_cluster + mock_val = azure_resources.AzureCluster(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_azure_cluster_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_azure_cluster( + azure_service.UpdateAzureClusterRequest(), + azure_cluster=azure_resources.AzureCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureClusterRequest, + dict, +]) +def test_get_azure_cluster(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureCluster( + name='name_value', + description='description_value', + azure_region='azure_region_value', + resource_group_id='resource_group_id_value', + azure_client='azure_client_value', + state=azure_resources.AzureCluster.State.PROVISIONING, + endpoint='endpoint_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + cluster_ca_certificate='cluster_ca_certificate_value', + ) + response = client.get_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureCluster) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.azure_region == 'azure_region_value' + assert response.resource_group_id == 'resource_group_id_value' + assert response.azure_client == 'azure_client_value' + assert response.state == azure_resources.AzureCluster.State.PROVISIONING + assert response.endpoint == 'endpoint_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' + + +def test_get_azure_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.GetAzureClusterRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_azure_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.GetAzureClusterRequest( + name='name_value', + ) + +def test_get_azure_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_cluster] = mock_rpc + request = {} + client.get_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_azure_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_azure_cluster] = mock_rpc + + request = {} + await client.get_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_cluster_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureClusterRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureCluster( + name='name_value', + description='description_value', + azure_region='azure_region_value', + resource_group_id='resource_group_id_value', + azure_client='azure_client_value', + state=azure_resources.AzureCluster.State.PROVISIONING, + endpoint='endpoint_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + cluster_ca_certificate='cluster_ca_certificate_value', + )) + response = await client.get_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureCluster) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.azure_region == 'azure_region_value' + assert response.resource_group_id == 'resource_group_id_value' + assert response.azure_client == 'azure_client_value' + assert response.state == azure_resources.AzureCluster.State.PROVISIONING + assert response.endpoint == 'endpoint_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' + + +@pytest.mark.asyncio +async def test_get_azure_cluster_async_from_dict(): + await test_get_azure_cluster_async(request_type=dict) + +def test_get_azure_cluster_field_headers(): + client = AzureClustersClient( + 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 = azure_service.GetAzureClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_cluster), + '__call__') as call: + call.return_value = azure_resources.AzureCluster() + client.get_azure_cluster(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_azure_cluster_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.GetAzureClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureCluster()) + await client.get_azure_cluster(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_azure_cluster_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureCluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_azure_cluster( + 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_azure_cluster_flattened_error(): + client = AzureClustersClient( + 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_azure_cluster( + azure_service.GetAzureClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_azure_cluster_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureCluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureCluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_azure_cluster( + 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_azure_cluster_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_azure_cluster( + azure_service.GetAzureClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.ListAzureClustersRequest, + dict, +]) +def test_list_azure_clusters(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.ListAzureClustersResponse( + next_page_token='next_page_token_value', + ) + response = client.list_azure_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.ListAzureClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAzureClustersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_azure_clusters_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.ListAzureClustersRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clusters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_azure_clusters(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.ListAzureClustersRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_azure_clusters_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_azure_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_azure_clusters] = mock_rpc + request = {} + client.list_azure_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_azure_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_azure_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_azure_clusters in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_azure_clusters] = mock_rpc + + request = {} + await client.list_azure_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_azure_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_azure_clusters_async(transport: str = 'grpc_asyncio', request_type=azure_service.ListAzureClustersRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClustersResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_azure_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.ListAzureClustersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAzureClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_azure_clusters_async_from_dict(): + await test_list_azure_clusters_async(request_type=dict) + +def test_list_azure_clusters_field_headers(): + client = AzureClustersClient( + 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 = azure_service.ListAzureClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clusters), + '__call__') as call: + call.return_value = azure_service.ListAzureClustersResponse() + client.list_azure_clusters(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_azure_clusters_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.ListAzureClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClustersResponse()) + await client.list_azure_clusters(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_azure_clusters_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.ListAzureClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_azure_clusters( + 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_azure_clusters_flattened_error(): + client = AzureClustersClient( + 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_azure_clusters( + azure_service.ListAzureClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_azure_clusters_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.ListAzureClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_azure_clusters( + 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_azure_clusters_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_azure_clusters( + azure_service.ListAzureClustersRequest(), + parent='parent_value', + ) + + +def test_list_azure_clusters_pager(transport_name: str = "grpc"): + client = AzureClustersClient( + 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_azure_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + ], + next_page_token='abc', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[], + next_page_token='def', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_azure_clusters(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, azure_resources.AzureCluster) + for i in results) +def test_list_azure_clusters_pages(transport_name: str = "grpc"): + client = AzureClustersClient( + 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_azure_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + ], + next_page_token='abc', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[], + next_page_token='def', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_azure_clusters(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_azure_clusters_async_pager(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + ], + next_page_token='abc', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[], + next_page_token='def', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_azure_clusters(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, azure_resources.AzureCluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_azure_clusters_async_pages(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + ], + next_page_token='abc', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[], + next_page_token='def', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + ], + ), + 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_azure_clusters(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", [ + azure_service.DeleteAzureClusterRequest, + dict, +]) +def test_delete_azure_cluster(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.DeleteAzureClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_azure_cluster_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.DeleteAzureClusterRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_cluster), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_azure_cluster(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.DeleteAzureClusterRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_azure_cluster_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_azure_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_azure_cluster] = mock_rpc + request = {} + client.delete_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_azure_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_azure_cluster in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_azure_cluster] = mock_rpc + + request = {} + await client.delete_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_azure_cluster_async(transport: str = 'grpc_asyncio', request_type=azure_service.DeleteAzureClusterRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_cluster), + '__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_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.DeleteAzureClusterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_azure_cluster_async_from_dict(): + await test_delete_azure_cluster_async(request_type=dict) + +def test_delete_azure_cluster_field_headers(): + client = AzureClustersClient( + 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 = azure_service.DeleteAzureClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_azure_cluster(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_azure_cluster_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.DeleteAzureClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_azure_cluster(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_azure_cluster_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_cluster), + '__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_azure_cluster( + 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_azure_cluster_flattened_error(): + client = AzureClustersClient( + 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_azure_cluster( + azure_service.DeleteAzureClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_azure_cluster_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_cluster), + '__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_azure_cluster( + 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_azure_cluster_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_azure_cluster( + azure_service.DeleteAzureClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GenerateAzureClusterAgentTokenRequest, + dict, +]) +def test_generate_azure_cluster_agent_token(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_cluster_agent_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.GenerateAzureClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + ) + response = client.generate_azure_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.GenerateAzureClusterAgentTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_service.GenerateAzureClusterAgentTokenResponse) + assert response.access_token == 'access_token_value' + assert response.expires_in == 1078 + assert response.token_type == 'token_type_value' + + +def test_generate_azure_cluster_agent_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.GenerateAzureClusterAgentTokenRequest( + azure_cluster='azure_cluster_value', + subject_token='subject_token_value', + subject_token_type='subject_token_type_value', + version='version_value', + node_pool_id='node_pool_id_value', + grant_type='grant_type_value', + audience='audience_value', + scope='scope_value', + requested_token_type='requested_token_type_value', + options='options_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_cluster_agent_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_azure_cluster_agent_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.GenerateAzureClusterAgentTokenRequest( + azure_cluster='azure_cluster_value', + subject_token='subject_token_value', + subject_token_type='subject_token_type_value', + version='version_value', + node_pool_id='node_pool_id_value', + grant_type='grant_type_value', + audience='audience_value', + scope='scope_value', + requested_token_type='requested_token_type_value', + options='options_value', + ) + +def test_generate_azure_cluster_agent_token_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_azure_cluster_agent_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_azure_cluster_agent_token] = mock_rpc + request = {} + client.generate_azure_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_azure_cluster_agent_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_azure_cluster_agent_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_azure_cluster_agent_token in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.generate_azure_cluster_agent_token] = mock_rpc + + request = {} + await client.generate_azure_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_azure_cluster_agent_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_azure_cluster_agent_token_async(transport: str = 'grpc_asyncio', request_type=azure_service.GenerateAzureClusterAgentTokenRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_cluster_agent_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + )) + response = await client.generate_azure_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.GenerateAzureClusterAgentTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_service.GenerateAzureClusterAgentTokenResponse) + assert response.access_token == 'access_token_value' + assert response.expires_in == 1078 + assert response.token_type == 'token_type_value' + + +@pytest.mark.asyncio +async def test_generate_azure_cluster_agent_token_async_from_dict(): + await test_generate_azure_cluster_agent_token_async(request_type=dict) + +def test_generate_azure_cluster_agent_token_field_headers(): + client = AzureClustersClient( + 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 = azure_service.GenerateAzureClusterAgentTokenRequest() + + request.azure_cluster = 'azure_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_cluster_agent_token), + '__call__') as call: + call.return_value = azure_service.GenerateAzureClusterAgentTokenResponse() + client.generate_azure_cluster_agent_token(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', + 'azure_cluster=azure_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_azure_cluster_agent_token_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.GenerateAzureClusterAgentTokenRequest() + + request.azure_cluster = 'azure_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_cluster_agent_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureClusterAgentTokenResponse()) + await client.generate_azure_cluster_agent_token(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', + 'azure_cluster=azure_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + azure_service.GenerateAzureAccessTokenRequest, + dict, +]) +def test_generate_azure_access_token(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.GenerateAzureAccessTokenResponse( + access_token='access_token_value', + ) + response = client.generate_azure_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.GenerateAzureAccessTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_service.GenerateAzureAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +def test_generate_azure_access_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.GenerateAzureAccessTokenRequest( + azure_cluster='azure_cluster_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_access_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_azure_access_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.GenerateAzureAccessTokenRequest( + azure_cluster='azure_cluster_value', + ) + +def test_generate_azure_access_token_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_azure_access_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_azure_access_token] = mock_rpc + request = {} + client.generate_azure_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_azure_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_azure_access_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_azure_access_token in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.generate_azure_access_token] = mock_rpc + + request = {} + await client.generate_azure_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_azure_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_azure_access_token_async(transport: str = 'grpc_asyncio', request_type=azure_service.GenerateAzureAccessTokenRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureAccessTokenResponse( + access_token='access_token_value', + )) + response = await client.generate_azure_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.GenerateAzureAccessTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_service.GenerateAzureAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +@pytest.mark.asyncio +async def test_generate_azure_access_token_async_from_dict(): + await test_generate_azure_access_token_async(request_type=dict) + +def test_generate_azure_access_token_field_headers(): + client = AzureClustersClient( + 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 = azure_service.GenerateAzureAccessTokenRequest() + + request.azure_cluster = 'azure_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_access_token), + '__call__') as call: + call.return_value = azure_service.GenerateAzureAccessTokenResponse() + client.generate_azure_access_token(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', + 'azure_cluster=azure_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_azure_access_token_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.GenerateAzureAccessTokenRequest() + + request.azure_cluster = 'azure_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_access_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureAccessTokenResponse()) + await client.generate_azure_access_token(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', + 'azure_cluster=azure_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + azure_service.CreateAzureNodePoolRequest, + dict, +]) +def test_create_azure_node_pool(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.CreateAzureNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_azure_node_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.CreateAzureNodePoolRequest( + parent='parent_value', + azure_node_pool_id='azure_node_pool_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_node_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_azure_node_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.CreateAzureNodePoolRequest( + parent='parent_value', + azure_node_pool_id='azure_node_pool_id_value', + ) + +def test_create_azure_node_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_azure_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_azure_node_pool] = mock_rpc + request = {} + client.create_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_azure_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_azure_node_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_azure_node_pool] = mock_rpc + + request = {} + await client.create_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_azure_node_pool_async(transport: str = 'grpc_asyncio', request_type=azure_service.CreateAzureNodePoolRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_node_pool), + '__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_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.CreateAzureNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_azure_node_pool_async_from_dict(): + await test_create_azure_node_pool_async(request_type=dict) + +def test_create_azure_node_pool_field_headers(): + client = AzureClustersClient( + 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 = azure_service.CreateAzureNodePoolRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_azure_node_pool(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_azure_node_pool_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.CreateAzureNodePoolRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_node_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_azure_node_pool(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_azure_node_pool_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_node_pool), + '__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_azure_node_pool( + parent='parent_value', + azure_node_pool=azure_resources.AzureNodePool(name='name_value'), + azure_node_pool_id='azure_node_pool_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].azure_node_pool + mock_val = azure_resources.AzureNodePool(name='name_value') + assert arg == mock_val + arg = args[0].azure_node_pool_id + mock_val = 'azure_node_pool_id_value' + assert arg == mock_val + + +def test_create_azure_node_pool_flattened_error(): + client = AzureClustersClient( + 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_azure_node_pool( + azure_service.CreateAzureNodePoolRequest(), + parent='parent_value', + azure_node_pool=azure_resources.AzureNodePool(name='name_value'), + azure_node_pool_id='azure_node_pool_id_value', + ) + +@pytest.mark.asyncio +async def test_create_azure_node_pool_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_node_pool), + '__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_azure_node_pool( + parent='parent_value', + azure_node_pool=azure_resources.AzureNodePool(name='name_value'), + azure_node_pool_id='azure_node_pool_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].azure_node_pool + mock_val = azure_resources.AzureNodePool(name='name_value') + assert arg == mock_val + arg = args[0].azure_node_pool_id + mock_val = 'azure_node_pool_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_azure_node_pool_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_azure_node_pool( + azure_service.CreateAzureNodePoolRequest(), + parent='parent_value', + azure_node_pool=azure_resources.AzureNodePool(name='name_value'), + azure_node_pool_id='azure_node_pool_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.UpdateAzureNodePoolRequest, + dict, +]) +def test_update_azure_node_pool(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.UpdateAzureNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_azure_node_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.UpdateAzureNodePoolRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_node_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_azure_node_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.UpdateAzureNodePoolRequest( + ) + +def test_update_azure_node_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_azure_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_azure_node_pool] = mock_rpc + request = {} + client.update_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_azure_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_azure_node_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_azure_node_pool] = mock_rpc + + request = {} + await client.update_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_azure_node_pool_async(transport: str = 'grpc_asyncio', request_type=azure_service.UpdateAzureNodePoolRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_node_pool), + '__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_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.UpdateAzureNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_azure_node_pool_async_from_dict(): + await test_update_azure_node_pool_async(request_type=dict) + +def test_update_azure_node_pool_field_headers(): + client = AzureClustersClient( + 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 = azure_service.UpdateAzureNodePoolRequest() + + request.azure_node_pool.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_azure_node_pool(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', + 'azure_node_pool.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_azure_node_pool_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.UpdateAzureNodePoolRequest() + + request.azure_node_pool.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_node_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_azure_node_pool(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', + 'azure_node_pool.name=name_value', + ) in kw['metadata'] + + +def test_update_azure_node_pool_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_node_pool), + '__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_azure_node_pool( + azure_node_pool=azure_resources.AzureNodePool(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].azure_node_pool + mock_val = azure_resources.AzureNodePool(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_azure_node_pool_flattened_error(): + client = AzureClustersClient( + 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_azure_node_pool( + azure_service.UpdateAzureNodePoolRequest(), + azure_node_pool=azure_resources.AzureNodePool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_azure_node_pool_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_node_pool), + '__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_azure_node_pool( + azure_node_pool=azure_resources.AzureNodePool(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].azure_node_pool + mock_val = azure_resources.AzureNodePool(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_azure_node_pool_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_azure_node_pool( + azure_service.UpdateAzureNodePoolRequest(), + azure_node_pool=azure_resources.AzureNodePool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureNodePoolRequest, + dict, +]) +def test_get_azure_node_pool(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureNodePool( + name='name_value', + version='version_value', + subnet_id='subnet_id_value', + state=azure_resources.AzureNodePool.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + azure_availability_zone='azure_availability_zone_value', + ) + response = client.get_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureNodePool) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.subnet_id == 'subnet_id_value' + assert response.state == azure_resources.AzureNodePool.State.PROVISIONING + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.azure_availability_zone == 'azure_availability_zone_value' + + +def test_get_azure_node_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.GetAzureNodePoolRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_node_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_azure_node_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.GetAzureNodePoolRequest( + name='name_value', + ) + +def test_get_azure_node_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_node_pool] = mock_rpc + request = {} + client.get_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_azure_node_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_azure_node_pool] = mock_rpc + + request = {} + await client.get_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_node_pool_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureNodePoolRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureNodePool( + name='name_value', + version='version_value', + subnet_id='subnet_id_value', + state=azure_resources.AzureNodePool.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + azure_availability_zone='azure_availability_zone_value', + )) + response = await client.get_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureNodePool) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.subnet_id == 'subnet_id_value' + assert response.state == azure_resources.AzureNodePool.State.PROVISIONING + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.azure_availability_zone == 'azure_availability_zone_value' + + +@pytest.mark.asyncio +async def test_get_azure_node_pool_async_from_dict(): + await test_get_azure_node_pool_async(request_type=dict) + +def test_get_azure_node_pool_field_headers(): + client = AzureClustersClient( + 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 = azure_service.GetAzureNodePoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_node_pool), + '__call__') as call: + call.return_value = azure_resources.AzureNodePool() + client.get_azure_node_pool(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_azure_node_pool_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.GetAzureNodePoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_node_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureNodePool()) + await client.get_azure_node_pool(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_azure_node_pool_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureNodePool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_azure_node_pool( + 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_azure_node_pool_flattened_error(): + client = AzureClustersClient( + 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_azure_node_pool( + azure_service.GetAzureNodePoolRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_azure_node_pool_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureNodePool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureNodePool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_azure_node_pool( + 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_azure_node_pool_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_azure_node_pool( + azure_service.GetAzureNodePoolRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.ListAzureNodePoolsRequest, + dict, +]) +def test_list_azure_node_pools(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_node_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.ListAzureNodePoolsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_azure_node_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.ListAzureNodePoolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAzureNodePoolsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_azure_node_pools_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.ListAzureNodePoolsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_node_pools), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_azure_node_pools(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.ListAzureNodePoolsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_azure_node_pools_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_azure_node_pools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_azure_node_pools] = mock_rpc + request = {} + client.list_azure_node_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_azure_node_pools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_azure_node_pools_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_azure_node_pools in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_azure_node_pools] = mock_rpc + + request = {} + await client.list_azure_node_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_azure_node_pools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_azure_node_pools_async(transport: str = 'grpc_asyncio', request_type=azure_service.ListAzureNodePoolsRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_node_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureNodePoolsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_azure_node_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.ListAzureNodePoolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAzureNodePoolsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_azure_node_pools_async_from_dict(): + await test_list_azure_node_pools_async(request_type=dict) + +def test_list_azure_node_pools_field_headers(): + client = AzureClustersClient( + 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 = azure_service.ListAzureNodePoolsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_node_pools), + '__call__') as call: + call.return_value = azure_service.ListAzureNodePoolsResponse() + client.list_azure_node_pools(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_azure_node_pools_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.ListAzureNodePoolsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_node_pools), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureNodePoolsResponse()) + await client.list_azure_node_pools(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_azure_node_pools_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_node_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.ListAzureNodePoolsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_azure_node_pools( + 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_azure_node_pools_flattened_error(): + client = AzureClustersClient( + 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_azure_node_pools( + azure_service.ListAzureNodePoolsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_azure_node_pools_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_node_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_service.ListAzureNodePoolsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureNodePoolsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_azure_node_pools( + 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_azure_node_pools_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_azure_node_pools( + azure_service.ListAzureNodePoolsRequest(), + parent='parent_value', + ) + + +def test_list_azure_node_pools_pager(transport_name: str = "grpc"): + client = AzureClustersClient( + 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_azure_node_pools), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + ], + next_page_token='abc', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[], + next_page_token='def', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_azure_node_pools(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, azure_resources.AzureNodePool) + for i in results) +def test_list_azure_node_pools_pages(transport_name: str = "grpc"): + client = AzureClustersClient( + 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_azure_node_pools), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + ], + next_page_token='abc', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[], + next_page_token='def', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + ], + ), + RuntimeError, + ) + pages = list(client.list_azure_node_pools(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_azure_node_pools_async_pager(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_node_pools), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + ], + next_page_token='abc', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[], + next_page_token='def', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_azure_node_pools(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, azure_resources.AzureNodePool) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_azure_node_pools_async_pages(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_node_pools), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + ], + next_page_token='abc', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[], + next_page_token='def', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + ], + ), + 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_azure_node_pools(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", [ + azure_service.DeleteAzureNodePoolRequest, + dict, +]) +def test_delete_azure_node_pool(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.DeleteAzureNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_azure_node_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.DeleteAzureNodePoolRequest( + name='name_value', + etag='etag_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_node_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_azure_node_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.DeleteAzureNodePoolRequest( + name='name_value', + etag='etag_value', + ) + +def test_delete_azure_node_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_azure_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_azure_node_pool] = mock_rpc + request = {} + client.delete_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_azure_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_azure_node_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_azure_node_pool] = mock_rpc + + request = {} + await client.delete_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_azure_node_pool_async(transport: str = 'grpc_asyncio', request_type=azure_service.DeleteAzureNodePoolRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_node_pool), + '__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_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.DeleteAzureNodePoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_azure_node_pool_async_from_dict(): + await test_delete_azure_node_pool_async(request_type=dict) + +def test_delete_azure_node_pool_field_headers(): + client = AzureClustersClient( + 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 = azure_service.DeleteAzureNodePoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_azure_node_pool(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_azure_node_pool_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.DeleteAzureNodePoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_node_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_azure_node_pool(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_azure_node_pool_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_node_pool), + '__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_azure_node_pool( + 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_azure_node_pool_flattened_error(): + client = AzureClustersClient( + 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_azure_node_pool( + azure_service.DeleteAzureNodePoolRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_azure_node_pool_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_node_pool), + '__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_azure_node_pool( + 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_azure_node_pool_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_azure_node_pool( + azure_service.DeleteAzureNodePoolRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureOpenIdConfigRequest, + dict, +]) +def test_get_azure_open_id_config(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_open_id_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureOpenIdConfig( + issuer='issuer_value', + jwks_uri='jwks_uri_value', + response_types_supported=['response_types_supported_value'], + subject_types_supported=['subject_types_supported_value'], + id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], + claims_supported=['claims_supported_value'], + grant_types=['grant_types_value'], + ) + response = client.get_azure_open_id_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureOpenIdConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureOpenIdConfig) + assert response.issuer == 'issuer_value' + assert response.jwks_uri == 'jwks_uri_value' + assert response.response_types_supported == ['response_types_supported_value'] + assert response.subject_types_supported == ['subject_types_supported_value'] + assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] + assert response.claims_supported == ['claims_supported_value'] + assert response.grant_types == ['grant_types_value'] + + +def test_get_azure_open_id_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.GetAzureOpenIdConfigRequest( + azure_cluster='azure_cluster_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_open_id_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_azure_open_id_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.GetAzureOpenIdConfigRequest( + azure_cluster='azure_cluster_value', + ) + +def test_get_azure_open_id_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_open_id_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_open_id_config] = mock_rpc + request = {} + client.get_azure_open_id_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_open_id_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_open_id_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_azure_open_id_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_azure_open_id_config] = mock_rpc + + request = {} + await client.get_azure_open_id_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_azure_open_id_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_open_id_config_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureOpenIdConfigRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_open_id_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureOpenIdConfig( + issuer='issuer_value', + jwks_uri='jwks_uri_value', + response_types_supported=['response_types_supported_value'], + subject_types_supported=['subject_types_supported_value'], + id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], + claims_supported=['claims_supported_value'], + grant_types=['grant_types_value'], + )) + response = await client.get_azure_open_id_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureOpenIdConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureOpenIdConfig) + assert response.issuer == 'issuer_value' + assert response.jwks_uri == 'jwks_uri_value' + assert response.response_types_supported == ['response_types_supported_value'] + assert response.subject_types_supported == ['subject_types_supported_value'] + assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] + assert response.claims_supported == ['claims_supported_value'] + assert response.grant_types == ['grant_types_value'] + + +@pytest.mark.asyncio +async def test_get_azure_open_id_config_async_from_dict(): + await test_get_azure_open_id_config_async(request_type=dict) + +def test_get_azure_open_id_config_field_headers(): + client = AzureClustersClient( + 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 = azure_service.GetAzureOpenIdConfigRequest() + + request.azure_cluster = 'azure_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_open_id_config), + '__call__') as call: + call.return_value = azure_resources.AzureOpenIdConfig() + client.get_azure_open_id_config(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', + 'azure_cluster=azure_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_azure_open_id_config_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.GetAzureOpenIdConfigRequest() + + request.azure_cluster = 'azure_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_open_id_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureOpenIdConfig()) + await client.get_azure_open_id_config(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', + 'azure_cluster=azure_cluster_value', + ) in kw['metadata'] + + +def test_get_azure_open_id_config_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_open_id_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureOpenIdConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_azure_open_id_config( + azure_cluster='azure_cluster_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].azure_cluster + mock_val = 'azure_cluster_value' + assert arg == mock_val + + +def test_get_azure_open_id_config_flattened_error(): + client = AzureClustersClient( + 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_azure_open_id_config( + azure_service.GetAzureOpenIdConfigRequest(), + azure_cluster='azure_cluster_value', + ) + +@pytest.mark.asyncio +async def test_get_azure_open_id_config_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_open_id_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureOpenIdConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureOpenIdConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_azure_open_id_config( + azure_cluster='azure_cluster_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].azure_cluster + mock_val = 'azure_cluster_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_azure_open_id_config_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_azure_open_id_config( + azure_service.GetAzureOpenIdConfigRequest(), + azure_cluster='azure_cluster_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureJsonWebKeysRequest, + dict, +]) +def test_get_azure_json_web_keys(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_json_web_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureJsonWebKeys( + ) + response = client.get_azure_json_web_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureJsonWebKeysRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureJsonWebKeys) + + +def test_get_azure_json_web_keys_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.GetAzureJsonWebKeysRequest( + azure_cluster='azure_cluster_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_json_web_keys), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_azure_json_web_keys(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.GetAzureJsonWebKeysRequest( + azure_cluster='azure_cluster_value', + ) + +def test_get_azure_json_web_keys_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_json_web_keys in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_json_web_keys] = mock_rpc + request = {} + client.get_azure_json_web_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_json_web_keys(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_json_web_keys_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_azure_json_web_keys in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_azure_json_web_keys] = mock_rpc + + request = {} + await client.get_azure_json_web_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_azure_json_web_keys(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_json_web_keys_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureJsonWebKeysRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_json_web_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureJsonWebKeys( + )) + response = await client.get_azure_json_web_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureJsonWebKeysRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureJsonWebKeys) + + +@pytest.mark.asyncio +async def test_get_azure_json_web_keys_async_from_dict(): + await test_get_azure_json_web_keys_async(request_type=dict) + +def test_get_azure_json_web_keys_field_headers(): + client = AzureClustersClient( + 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 = azure_service.GetAzureJsonWebKeysRequest() + + request.azure_cluster = 'azure_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_json_web_keys), + '__call__') as call: + call.return_value = azure_resources.AzureJsonWebKeys() + client.get_azure_json_web_keys(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', + 'azure_cluster=azure_cluster_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_azure_json_web_keys_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.GetAzureJsonWebKeysRequest() + + request.azure_cluster = 'azure_cluster_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_json_web_keys), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureJsonWebKeys()) + await client.get_azure_json_web_keys(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', + 'azure_cluster=azure_cluster_value', + ) in kw['metadata'] + + +def test_get_azure_json_web_keys_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_json_web_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureJsonWebKeys() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_azure_json_web_keys( + azure_cluster='azure_cluster_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].azure_cluster + mock_val = 'azure_cluster_value' + assert arg == mock_val + + +def test_get_azure_json_web_keys_flattened_error(): + client = AzureClustersClient( + 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_azure_json_web_keys( + azure_service.GetAzureJsonWebKeysRequest(), + azure_cluster='azure_cluster_value', + ) + +@pytest.mark.asyncio +async def test_get_azure_json_web_keys_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_json_web_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureJsonWebKeys() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureJsonWebKeys()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_azure_json_web_keys( + azure_cluster='azure_cluster_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].azure_cluster + mock_val = 'azure_cluster_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_azure_json_web_keys_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_azure_json_web_keys( + azure_service.GetAzureJsonWebKeysRequest(), + azure_cluster='azure_cluster_value', + ) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureServerConfigRequest, + dict, +]) +def test_get_azure_server_config(request_type, transport: str = 'grpc'): + client = AzureClustersClient( + 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_azure_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureServerConfig( + name='name_value', + supported_azure_regions=['supported_azure_regions_value'], + ) + response = client.get_azure_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureServerConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureServerConfig) + assert response.name == 'name_value' + assert response.supported_azure_regions == ['supported_azure_regions_value'] + + +def test_get_azure_server_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = azure_service.GetAzureServerConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_server_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_azure_server_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == azure_service.GetAzureServerConfigRequest( + name='name_value', + ) + +def test_get_azure_server_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_server_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_server_config] = mock_rpc + request = {} + client.get_azure_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_server_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_server_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_azure_server_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_azure_server_config] = mock_rpc + + request = {} + await client.get_azure_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_azure_server_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_azure_server_config_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureServerConfigRequest): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_azure_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureServerConfig( + name='name_value', + supported_azure_regions=['supported_azure_regions_value'], + )) + response = await client.get_azure_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = azure_service.GetAzureServerConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureServerConfig) + assert response.name == 'name_value' + assert response.supported_azure_regions == ['supported_azure_regions_value'] + + +@pytest.mark.asyncio +async def test_get_azure_server_config_async_from_dict(): + await test_get_azure_server_config_async(request_type=dict) + +def test_get_azure_server_config_field_headers(): + client = AzureClustersClient( + 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 = azure_service.GetAzureServerConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_server_config), + '__call__') as call: + call.return_value = azure_resources.AzureServerConfig() + client.get_azure_server_config(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_azure_server_config_field_headers_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = azure_service.GetAzureServerConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_server_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureServerConfig()) + await client.get_azure_server_config(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_azure_server_config_flattened(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureServerConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_azure_server_config( + 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_azure_server_config_flattened_error(): + client = AzureClustersClient( + 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_azure_server_config( + azure_service.GetAzureServerConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_azure_server_config_flattened_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = azure_resources.AzureServerConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureServerConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_azure_server_config( + 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_azure_server_config_flattened_error_async(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_azure_server_config( + azure_service.GetAzureServerConfigRequest(), + name='name_value', + ) + + +def test_create_azure_client_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_azure_client in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_azure_client] = mock_rpc + + request = {} + client.create_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_azure_client(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_azure_client_rest_required_fields(request_type=azure_service.CreateAzureClientRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["azure_client_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "azureClientId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_client._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "azureClientId" in jsonified_request + assert jsonified_request["azureClientId"] == request_init["azure_client_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["azureClientId"] = 'azure_client_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_client._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("azure_client_id", "validate_only", )) + 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 "azureClientId" in jsonified_request + assert jsonified_request["azureClientId"] == 'azure_client_id_value' + + client = AzureClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_azure_client(request) + + expected_params = [ + ( + "azureClientId", + "", + ), + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_azure_client_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_azure_client._get_unset_required_fields({}) + assert set(unset_fields) == (set(("azureClientId", "validateOnly", )) & set(("parent", "azureClient", "azureClientId", ))) + + +def test_create_azure_client_rest_flattened(): + client = AzureClustersClient( + 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', + azure_client=azure_resources.AzureClient(name='name_value'), + azure_client_id='azure_client_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_azure_client(**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/*}/azureClients" % client.transport._host, args[1]) + + +def test_create_azure_client_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_client( + azure_service.CreateAzureClientRequest(), + parent='parent_value', + azure_client=azure_resources.AzureClient(name='name_value'), + azure_client_id='azure_client_id_value', + ) + + +def test_get_azure_client_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_client in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_client] = mock_rpc + + request = {} + client.get_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_client(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_azure_client_rest_required_fields(request_type=azure_service.GetAzureClientRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_client._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_azure_client._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 = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_resources.AzureClient() + # 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 = azure_resources.AzureClient.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_azure_client(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_azure_client_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_azure_client._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_azure_client_rest_flattened(): + client = AzureClustersClient( + 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 = azure_resources.AzureClient() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/azureClients/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 = azure_resources.AzureClient.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_azure_client(**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/*/azureClients/*}" % client.transport._host, args[1]) + + +def test_get_azure_client_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_client( + azure_service.GetAzureClientRequest(), + name='name_value', + ) + + +def test_list_azure_clients_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_azure_clients in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_azure_clients] = mock_rpc + + request = {} + client.list_azure_clients(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_azure_clients(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_azure_clients_rest_required_fields(request_type=azure_service.ListAzureClientsRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_azure_clients._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_azure_clients._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + 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 = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_service.ListAzureClientsResponse() + # 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 = azure_service.ListAzureClientsResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_azure_clients(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_azure_clients_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_azure_clients._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_azure_clients_rest_flattened(): + client = AzureClustersClient( + 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 = azure_service.ListAzureClientsResponse() + + # 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 = azure_service.ListAzureClientsResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_azure_clients(**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/*}/azureClients" % client.transport._host, args[1]) + + +def test_list_azure_clients_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_clients( + azure_service.ListAzureClientsRequest(), + parent='parent_value', + ) + + +def test_list_azure_clients_rest_pager(transport: str = 'rest'): + client = AzureClustersClient( + 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 = ( + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + azure_resources.AzureClient(), + azure_resources.AzureClient(), + ], + next_page_token='abc', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[], + next_page_token='def', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureClientsResponse( + azure_clients=[ + azure_resources.AzureClient(), + azure_resources.AzureClient(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(azure_service.ListAzureClientsResponse.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_azure_clients(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, azure_resources.AzureClient) + for i in results) + + pages = list(client.list_azure_clients(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_azure_client_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_azure_client in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_azure_client] = mock_rpc + + request = {} + client.delete_azure_client(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_azure_client(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_azure_client_rest_required_fields(request_type=azure_service.DeleteAzureClientRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_azure_client._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_azure_client._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AzureClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_azure_client(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_azure_client_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_azure_client._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "validateOnly", )) & set(("name", ))) + + +def test_delete_azure_client_rest_flattened(): + client = AzureClustersClient( + 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/azureClients/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_azure_client(**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/*/azureClients/*}" % client.transport._host, args[1]) + + +def test_delete_azure_client_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_client( + azure_service.DeleteAzureClientRequest(), + name='name_value', + ) + + +def test_create_azure_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_azure_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_azure_cluster] = mock_rpc + + request = {} + client.create_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_azure_cluster_rest_required_fields(request_type=azure_service.CreateAzureClusterRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["azure_cluster_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "azureClusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "azureClusterId" in jsonified_request + assert jsonified_request["azureClusterId"] == request_init["azure_cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["azureClusterId"] = 'azure_cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("azure_cluster_id", "validate_only", )) + 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 "azureClusterId" in jsonified_request + assert jsonified_request["azureClusterId"] == 'azure_cluster_id_value' + + client = AzureClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_azure_cluster(request) + + expected_params = [ + ( + "azureClusterId", + "", + ), + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_azure_cluster_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_azure_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("azureClusterId", "validateOnly", )) & set(("parent", "azureCluster", "azureClusterId", ))) + + +def test_create_azure_cluster_rest_flattened(): + client = AzureClustersClient( + 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', + azure_cluster=azure_resources.AzureCluster(name='name_value'), + azure_cluster_id='azure_cluster_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_azure_cluster(**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/*}/azureClusters" % client.transport._host, args[1]) + + +def test_create_azure_cluster_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_cluster( + azure_service.CreateAzureClusterRequest(), + parent='parent_value', + azure_cluster=azure_resources.AzureCluster(name='name_value'), + azure_cluster_id='azure_cluster_id_value', + ) + + +def test_update_azure_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_azure_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_azure_cluster] = mock_rpc + + request = {} + client.update_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_azure_cluster_rest_required_fields(request_type=azure_service.UpdateAzureClusterRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_azure_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_azure_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AzureClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_azure_cluster(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_azure_cluster_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_azure_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("azureCluster", "updateMask", ))) + + +def test_update_azure_cluster_rest_flattened(): + client = AzureClustersClient( + 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 = {'azure_cluster': {'name': 'projects/sample1/locations/sample2/azureClusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + azure_cluster=azure_resources.AzureCluster(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_azure_cluster(**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/{azure_cluster.name=projects/*/locations/*/azureClusters/*}" % client.transport._host, args[1]) + + +def test_update_azure_cluster_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_cluster( + azure_service.UpdateAzureClusterRequest(), + azure_cluster=azure_resources.AzureCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_azure_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_cluster] = mock_rpc + + request = {} + client.get_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_azure_cluster_rest_required_fields(request_type=azure_service.GetAzureClusterRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_cluster._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_azure_cluster._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 = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_resources.AzureCluster() + # 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 = azure_resources.AzureCluster.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_azure_cluster(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_azure_cluster_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_azure_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_azure_cluster_rest_flattened(): + client = AzureClustersClient( + 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 = azure_resources.AzureCluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/azureClusters/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 = azure_resources.AzureCluster.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_azure_cluster(**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/*/azureClusters/*}" % client.transport._host, args[1]) + + +def test_get_azure_cluster_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_cluster( + azure_service.GetAzureClusterRequest(), + name='name_value', + ) + + +def test_list_azure_clusters_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_azure_clusters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_azure_clusters] = mock_rpc + + request = {} + client.list_azure_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_azure_clusters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_azure_clusters_rest_required_fields(request_type=azure_service.ListAzureClustersRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_azure_clusters._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_azure_clusters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + 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 = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_service.ListAzureClustersResponse() + # 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 = azure_service.ListAzureClustersResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_azure_clusters(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_azure_clusters_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_azure_clusters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_azure_clusters_rest_flattened(): + client = AzureClustersClient( + 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 = azure_service.ListAzureClustersResponse() + + # 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 = azure_service.ListAzureClustersResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_azure_clusters(**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/*}/azureClusters" % client.transport._host, args[1]) + + +def test_list_azure_clusters_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_clusters( + azure_service.ListAzureClustersRequest(), + parent='parent_value', + ) + + +def test_list_azure_clusters_rest_pager(transport: str = 'rest'): + client = AzureClustersClient( + 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 = ( + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + ], + next_page_token='abc', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[], + next_page_token='def', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureClustersResponse( + azure_clusters=[ + azure_resources.AzureCluster(), + azure_resources.AzureCluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(azure_service.ListAzureClustersResponse.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_azure_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, azure_resources.AzureCluster) + for i in results) + + pages = list(client.list_azure_clusters(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_azure_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_azure_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_azure_cluster] = mock_rpc + + request = {} + client.delete_azure_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_azure_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_azure_cluster_rest_required_fields(request_type=azure_service.DeleteAzureClusterRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_azure_cluster._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_azure_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "etag", "ignore_errors", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AzureClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_azure_cluster(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_azure_cluster_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_azure_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "etag", "ignoreErrors", "validateOnly", )) & set(("name", ))) + + +def test_delete_azure_cluster_rest_flattened(): + client = AzureClustersClient( + 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/azureClusters/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_azure_cluster(**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/*/azureClusters/*}" % client.transport._host, args[1]) + + +def test_delete_azure_cluster_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_cluster( + azure_service.DeleteAzureClusterRequest(), + name='name_value', + ) + + +def test_generate_azure_cluster_agent_token_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_azure_cluster_agent_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_azure_cluster_agent_token] = mock_rpc + + request = {} + client.generate_azure_cluster_agent_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_azure_cluster_agent_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_azure_cluster_agent_token_rest_required_fields(request_type=azure_service.GenerateAzureClusterAgentTokenRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["azure_cluster"] = "" + request_init["subject_token"] = "" + request_init["subject_token_type"] = "" + request_init["version"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_azure_cluster_agent_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["azureCluster"] = 'azure_cluster_value' + jsonified_request["subjectToken"] = 'subject_token_value' + jsonified_request["subjectTokenType"] = 'subject_token_type_value' + jsonified_request["version"] = 'version_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_azure_cluster_agent_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "azureCluster" in jsonified_request + assert jsonified_request["azureCluster"] == 'azure_cluster_value' + assert "subjectToken" in jsonified_request + assert jsonified_request["subjectToken"] == 'subject_token_value' + assert "subjectTokenType" in jsonified_request + assert jsonified_request["subjectTokenType"] == 'subject_token_type_value' + assert "version" in jsonified_request + assert jsonified_request["version"] == 'version_value' + + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_service.GenerateAzureClusterAgentTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_service.GenerateAzureClusterAgentTokenResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_azure_cluster_agent_token(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_azure_cluster_agent_token_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_azure_cluster_agent_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("azureCluster", "subjectToken", "subjectTokenType", "version", ))) + + +def test_generate_azure_access_token_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_azure_access_token in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_azure_access_token] = mock_rpc + + request = {} + client.generate_azure_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_azure_access_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_azure_access_token_rest_required_fields(request_type=azure_service.GenerateAzureAccessTokenRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["azure_cluster"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_azure_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["azureCluster"] = 'azure_cluster_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_azure_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "azureCluster" in jsonified_request + assert jsonified_request["azureCluster"] == 'azure_cluster_value' + + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_service.GenerateAzureAccessTokenResponse() + # 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 = azure_service.GenerateAzureAccessTokenResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_azure_access_token(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_azure_access_token_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_azure_access_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("azureCluster", ))) + + +def test_create_azure_node_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_azure_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_azure_node_pool] = mock_rpc + + request = {} + client.create_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_azure_node_pool_rest_required_fields(request_type=azure_service.CreateAzureNodePoolRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["azure_node_pool_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "azureNodePoolId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_node_pool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "azureNodePoolId" in jsonified_request + assert jsonified_request["azureNodePoolId"] == request_init["azure_node_pool_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["azureNodePoolId"] = 'azure_node_pool_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_node_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("azure_node_pool_id", "validate_only", )) + 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 "azureNodePoolId" in jsonified_request + assert jsonified_request["azureNodePoolId"] == 'azure_node_pool_id_value' + + client = AzureClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_azure_node_pool(request) + + expected_params = [ + ( + "azureNodePoolId", + "", + ), + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_azure_node_pool_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_azure_node_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("azureNodePoolId", "validateOnly", )) & set(("parent", "azureNodePool", "azureNodePoolId", ))) + + +def test_create_azure_node_pool_rest_flattened(): + client = AzureClustersClient( + 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/azureClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + azure_node_pool=azure_resources.AzureNodePool(name='name_value'), + azure_node_pool_id='azure_node_pool_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_azure_node_pool(**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/*/azureClusters/*}/azureNodePools" % client.transport._host, args[1]) + + +def test_create_azure_node_pool_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_node_pool( + azure_service.CreateAzureNodePoolRequest(), + parent='parent_value', + azure_node_pool=azure_resources.AzureNodePool(name='name_value'), + azure_node_pool_id='azure_node_pool_id_value', + ) + + +def test_update_azure_node_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_azure_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_azure_node_pool] = mock_rpc + + request = {} + client.update_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_azure_node_pool_rest_required_fields(request_type=azure_service.UpdateAzureNodePoolRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_azure_node_pool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_azure_node_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AzureClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_azure_node_pool(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_azure_node_pool_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_azure_node_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("azureNodePool", "updateMask", ))) + + +def test_update_azure_node_pool_rest_flattened(): + client = AzureClustersClient( + 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 = {'azure_node_pool': {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + azure_node_pool=azure_resources.AzureNodePool(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_azure_node_pool(**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/{azure_node_pool.name=projects/*/locations/*/azureClusters/*/azureNodePools/*}" % client.transport._host, args[1]) + + +def test_update_azure_node_pool_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_node_pool( + azure_service.UpdateAzureNodePoolRequest(), + azure_node_pool=azure_resources.AzureNodePool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_azure_node_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_node_pool] = mock_rpc + + request = {} + client.get_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_azure_node_pool_rest_required_fields(request_type=azure_service.GetAzureNodePoolRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_node_pool._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_azure_node_pool._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 = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_resources.AzureNodePool() + # 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 = azure_resources.AzureNodePool.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_azure_node_pool(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_azure_node_pool_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_azure_node_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_azure_node_pool_rest_flattened(): + client = AzureClustersClient( + 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 = azure_resources.AzureNodePool() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = azure_resources.AzureNodePool.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_azure_node_pool(**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/*/azureClusters/*/azureNodePools/*}" % client.transport._host, args[1]) + + +def test_get_azure_node_pool_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_node_pool( + azure_service.GetAzureNodePoolRequest(), + name='name_value', + ) + + +def test_list_azure_node_pools_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_azure_node_pools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_azure_node_pools] = mock_rpc + + request = {} + client.list_azure_node_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_azure_node_pools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_azure_node_pools_rest_required_fields(request_type=azure_service.ListAzureNodePoolsRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_azure_node_pools._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_azure_node_pools._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + 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 = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_service.ListAzureNodePoolsResponse() + # 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 = azure_service.ListAzureNodePoolsResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_azure_node_pools(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_azure_node_pools_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_azure_node_pools._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_azure_node_pools_rest_flattened(): + client = AzureClustersClient( + 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 = azure_service.ListAzureNodePoolsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/azureClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = azure_service.ListAzureNodePoolsResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_azure_node_pools(**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/*/azureClusters/*}/azureNodePools" % client.transport._host, args[1]) + + +def test_list_azure_node_pools_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_node_pools( + azure_service.ListAzureNodePoolsRequest(), + parent='parent_value', + ) + + +def test_list_azure_node_pools_rest_pager(transport: str = 'rest'): + client = AzureClustersClient( + 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 = ( + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + ], + next_page_token='abc', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[], + next_page_token='def', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + ], + next_page_token='ghi', + ), + azure_service.ListAzureNodePoolsResponse( + azure_node_pools=[ + azure_resources.AzureNodePool(), + azure_resources.AzureNodePool(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(azure_service.ListAzureNodePoolsResponse.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/azureClusters/sample3'} + + pager = client.list_azure_node_pools(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, azure_resources.AzureNodePool) + for i in results) + + pages = list(client.list_azure_node_pools(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_azure_node_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_azure_node_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_azure_node_pool] = mock_rpc + + request = {} + client.delete_azure_node_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_azure_node_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_azure_node_pool_rest_required_fields(request_type=azure_service.DeleteAzureNodePoolRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_azure_node_pool._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_azure_node_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "etag", "ignore_errors", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AzureClustersClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_azure_node_pool(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_azure_node_pool_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_azure_node_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "etag", "ignoreErrors", "validateOnly", )) & set(("name", ))) + + +def test_delete_azure_node_pool_rest_flattened(): + client = AzureClustersClient( + 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/azureClusters/sample3/azureNodePools/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_azure_node_pool(**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/*/azureClusters/*/azureNodePools/*}" % client.transport._host, args[1]) + + +def test_delete_azure_node_pool_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_node_pool( + azure_service.DeleteAzureNodePoolRequest(), + name='name_value', + ) + + +def test_get_azure_open_id_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_open_id_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_open_id_config] = mock_rpc + + request = {} + client.get_azure_open_id_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_open_id_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_azure_open_id_config_rest_required_fields(request_type=azure_service.GetAzureOpenIdConfigRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["azure_cluster"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_open_id_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["azureCluster"] = 'azure_cluster_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_open_id_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "azureCluster" in jsonified_request + assert jsonified_request["azureCluster"] == 'azure_cluster_value' + + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_resources.AzureOpenIdConfig() + # 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 = azure_resources.AzureOpenIdConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_azure_open_id_config(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_azure_open_id_config_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_azure_open_id_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("azureCluster", ))) + + +def test_get_azure_open_id_config_rest_flattened(): + client = AzureClustersClient( + 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 = azure_resources.AzureOpenIdConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + azure_cluster='azure_cluster_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 = azure_resources.AzureOpenIdConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_azure_open_id_config(**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/{azure_cluster=projects/*/locations/*/azureClusters/*}/.well-known/openid-configuration" % client.transport._host, args[1]) + + +def test_get_azure_open_id_config_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_open_id_config( + azure_service.GetAzureOpenIdConfigRequest(), + azure_cluster='azure_cluster_value', + ) + + +def test_get_azure_json_web_keys_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_json_web_keys in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_json_web_keys] = mock_rpc + + request = {} + client.get_azure_json_web_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_json_web_keys(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_azure_json_web_keys_rest_required_fields(request_type=azure_service.GetAzureJsonWebKeysRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["azure_cluster"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_json_web_keys._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["azureCluster"] = 'azure_cluster_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_json_web_keys._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "azureCluster" in jsonified_request + assert jsonified_request["azureCluster"] == 'azure_cluster_value' + + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_resources.AzureJsonWebKeys() + # 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 = azure_resources.AzureJsonWebKeys.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_azure_json_web_keys(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_azure_json_web_keys_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_azure_json_web_keys._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("azureCluster", ))) + + +def test_get_azure_json_web_keys_rest_flattened(): + client = AzureClustersClient( + 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 = azure_resources.AzureJsonWebKeys() + + # get arguments that satisfy an http rule for this method + sample_request = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + azure_cluster='azure_cluster_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 = azure_resources.AzureJsonWebKeys.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_azure_json_web_keys(**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/{azure_cluster=projects/*/locations/*/azureClusters/*}/jwks" % client.transport._host, args[1]) + + +def test_get_azure_json_web_keys_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_json_web_keys( + azure_service.GetAzureJsonWebKeysRequest(), + azure_cluster='azure_cluster_value', + ) + + +def test_get_azure_server_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_azure_server_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_azure_server_config] = mock_rpc + + request = {} + client.get_azure_server_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_azure_server_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_azure_server_config_rest_required_fields(request_type=azure_service.GetAzureServerConfigRequest): + transport_class = transports.AzureClustersRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_server_config._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_azure_server_config._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 = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = azure_resources.AzureServerConfig() + # 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 = azure_resources.AzureServerConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_azure_server_config(request) + + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_azure_server_config_rest_unset_required_fields(): + transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_azure_server_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_azure_server_config_rest_flattened(): + client = AzureClustersClient( + 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 = azure_resources.AzureServerConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/azureServerConfig'} + + # 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 = azure_resources.AzureServerConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_azure_server_config(**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/*/azureServerConfig}" % client.transport._host, args[1]) + + +def test_get_azure_server_config_rest_flattened_error(transport: str = 'rest'): + client = AzureClustersClient( + 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_azure_server_config( + azure_service.GetAzureServerConfigRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AzureClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AzureClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AzureClustersClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AzureClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AzureClustersClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AzureClustersClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AzureClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AzureClustersClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AzureClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AzureClustersClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AzureClustersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AzureClustersGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AzureClustersGrpcTransport, + transports.AzureClustersGrpcAsyncIOTransport, + transports.AzureClustersRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = AzureClustersClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_azure_client_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_client), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_azure_client(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.CreateAzureClientRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_client_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_client), + '__call__') as call: + call.return_value = azure_resources.AzureClient() + client.get_azure_client(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureClientRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_azure_clients_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clients), + '__call__') as call: + call.return_value = azure_service.ListAzureClientsResponse() + client.list_azure_clients(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.ListAzureClientsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_azure_client_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_client), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_azure_client(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.DeleteAzureClientRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_azure_cluster_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.CreateAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_azure_cluster_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.UpdateAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_cluster_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_cluster), + '__call__') as call: + call.return_value = azure_resources.AzureCluster() + client.get_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_azure_clusters_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clusters), + '__call__') as call: + call.return_value = azure_service.ListAzureClustersResponse() + client.list_azure_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.ListAzureClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_azure_cluster_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.DeleteAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_azure_cluster_agent_token_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_cluster_agent_token), + '__call__') as call: + call.return_value = azure_service.GenerateAzureClusterAgentTokenResponse() + client.generate_azure_cluster_agent_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GenerateAzureClusterAgentTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_azure_access_token_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_access_token), + '__call__') as call: + call.return_value = azure_service.GenerateAzureAccessTokenResponse() + client.generate_azure_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GenerateAzureAccessTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_azure_node_pool_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.CreateAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_azure_node_pool_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.UpdateAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_node_pool_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_node_pool), + '__call__') as call: + call.return_value = azure_resources.AzureNodePool() + client.get_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_azure_node_pools_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_node_pools), + '__call__') as call: + call.return_value = azure_service.ListAzureNodePoolsResponse() + client.list_azure_node_pools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.ListAzureNodePoolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_azure_node_pool_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_node_pool), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.DeleteAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_open_id_config_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_open_id_config), + '__call__') as call: + call.return_value = azure_resources.AzureOpenIdConfig() + client.get_azure_open_id_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureOpenIdConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_json_web_keys_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_json_web_keys), + '__call__') as call: + call.return_value = azure_resources.AzureJsonWebKeys() + client.get_azure_json_web_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureJsonWebKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_server_config_empty_call_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_server_config), + '__call__') as call: + call.return_value = azure_resources.AzureServerConfig() + client.get_azure_server_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureServerConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AzureClustersAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_azure_client_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_client), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_azure_client(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.CreateAzureClientRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_azure_client_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_client), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureClient( + name='name_value', + tenant_id='tenant_id_value', + application_id='application_id_value', + reconciling=True, + pem_certificate='pem_certificate_value', + uid='uid_value', + )) + await client.get_azure_client(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureClientRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_azure_clients_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clients), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClientsResponse( + next_page_token='next_page_token_value', + )) + await client.list_azure_clients(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.ListAzureClientsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_azure_client_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_client), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_azure_client(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.DeleteAzureClientRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_azure_cluster_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.CreateAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_azure_cluster_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.UpdateAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_azure_cluster_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureCluster( + name='name_value', + description='description_value', + azure_region='azure_region_value', + resource_group_id='resource_group_id_value', + azure_client='azure_client_value', + state=azure_resources.AzureCluster.State.PROVISIONING, + endpoint='endpoint_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + cluster_ca_certificate='cluster_ca_certificate_value', + )) + await client.get_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_azure_clusters_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClustersResponse( + next_page_token='next_page_token_value', + )) + await client.list_azure_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.ListAzureClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_azure_cluster_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.DeleteAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_azure_cluster_agent_token_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_cluster_agent_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + )) + await client.generate_azure_cluster_agent_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GenerateAzureClusterAgentTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_azure_access_token_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureAccessTokenResponse( + access_token='access_token_value', + )) + await client.generate_azure_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GenerateAzureAccessTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_azure_node_pool_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.CreateAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_azure_node_pool_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.UpdateAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_azure_node_pool_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureNodePool( + name='name_value', + version='version_value', + subnet_id='subnet_id_value', + state=azure_resources.AzureNodePool.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + azure_availability_zone='azure_availability_zone_value', + )) + await client.get_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_azure_node_pools_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_node_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureNodePoolsResponse( + next_page_token='next_page_token_value', + )) + await client.list_azure_node_pools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.ListAzureNodePoolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_azure_node_pool_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_node_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.DeleteAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_azure_open_id_config_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_open_id_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureOpenIdConfig( + issuer='issuer_value', + jwks_uri='jwks_uri_value', + response_types_supported=['response_types_supported_value'], + subject_types_supported=['subject_types_supported_value'], + id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], + claims_supported=['claims_supported_value'], + grant_types=['grant_types_value'], + )) + await client.get_azure_open_id_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureOpenIdConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_azure_json_web_keys_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_json_web_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureJsonWebKeys( + )) + await client.get_azure_json_web_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureJsonWebKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_azure_server_config_empty_call_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_server_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureServerConfig( + name='name_value', + supported_azure_regions=['supported_azure_regions_value'], + )) + await client.get_azure_server_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureServerConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AzureClustersClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_azure_client_rest_bad_request(request_type=azure_service.CreateAzureClientRequest): + client = AzureClustersClient( + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_azure_client(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.CreateAzureClientRequest, + dict, +]) +def test_create_azure_client_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["azure_client"] = {'name': 'name_value', 'tenant_id': 'tenant_id_value', 'application_id': 'application_id_value', 'reconciling': True, 'annotations': {}, 'pem_certificate': 'pem_certificate_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_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 = azure_service.CreateAzureClientRequest.meta.fields["azure_client"] + + 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["azure_client"].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["azure_client"][field])): + del request_init["azure_client"][field][i][subfield] + else: + del request_init["azure_client"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_azure_client(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_azure_client_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_create_azure_client") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_create_azure_client") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.CreateAzureClientRequest.pb(azure_service.CreateAzureClientRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = azure_service.CreateAzureClientRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_azure_client(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_azure_client_rest_bad_request(request_type=azure_service.GetAzureClientRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClients/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_azure_client(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureClientRequest, + dict, +]) +def test_get_azure_client_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClients/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 = azure_resources.AzureClient( + name='name_value', + tenant_id='tenant_id_value', + application_id='application_id_value', + reconciling=True, + pem_certificate='pem_certificate_value', + uid='uid_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_resources.AzureClient.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_azure_client(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureClient) + assert response.name == 'name_value' + assert response.tenant_id == 'tenant_id_value' + assert response.application_id == 'application_id_value' + assert response.reconciling is True + assert response.pem_certificate == 'pem_certificate_value' + assert response.uid == 'uid_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_azure_client_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_client") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_client") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.GetAzureClientRequest.pb(azure_service.GetAzureClientRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_resources.AzureClient.to_json(azure_resources.AzureClient()) + req.return_value.content = return_value + + request = azure_service.GetAzureClientRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_resources.AzureClient() + + client.get_azure_client(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_azure_clients_rest_bad_request(request_type=azure_service.ListAzureClientsRequest): + client = AzureClustersClient( + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_azure_clients(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.ListAzureClientsRequest, + dict, +]) +def test_list_azure_clients_rest_call_success(request_type): + client = AzureClustersClient( + 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 = azure_service.ListAzureClientsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_service.ListAzureClientsResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_azure_clients(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAzureClientsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_azure_clients_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_list_azure_clients") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_list_azure_clients") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.ListAzureClientsRequest.pb(azure_service.ListAzureClientsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_service.ListAzureClientsResponse.to_json(azure_service.ListAzureClientsResponse()) + req.return_value.content = return_value + + request = azure_service.ListAzureClientsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_service.ListAzureClientsResponse() + + client.list_azure_clients(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_azure_client_rest_bad_request(request_type=azure_service.DeleteAzureClientRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClients/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_azure_client(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.DeleteAzureClientRequest, + dict, +]) +def test_delete_azure_client_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClients/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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_azure_client(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_azure_client_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_delete_azure_client") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_delete_azure_client") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.DeleteAzureClientRequest.pb(azure_service.DeleteAzureClientRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = azure_service.DeleteAzureClientRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_azure_client(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_azure_cluster_rest_bad_request(request_type=azure_service.CreateAzureClusterRequest): + client = AzureClustersClient( + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_azure_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.CreateAzureClusterRequest, + dict, +]) +def test_create_azure_cluster_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["azure_cluster"] = {'name': 'name_value', 'description': 'description_value', 'azure_region': 'azure_region_value', 'resource_group_id': 'resource_group_id_value', 'azure_client': 'azure_client_value', 'networking': {'virtual_network_id': 'virtual_network_id_value', 'pod_address_cidr_blocks': ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'], 'service_address_cidr_blocks': ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'], 'service_load_balancer_subnet_id': 'service_load_balancer_subnet_id_value'}, 'control_plane': {'version': 'version_value', 'subnet_id': 'subnet_id_value', 'vm_size': 'vm_size_value', 'ssh_config': {'authorized_key': 'authorized_key_value'}, 'root_volume': {'size_gib': 844}, 'main_volume': {}, 'database_encryption': {'key_id': 'key_id_value'}, 'proxy_config': {'resource_group_id': 'resource_group_id_value', 'secret_id': 'secret_id_value'}, 'config_encryption': {'key_id': 'key_id_value', 'public_key': 'public_key_value'}, 'tags': {}, 'replica_placements': [{'subnet_id': 'subnet_id_value', 'azure_availability_zone': 'azure_availability_zone_value'}], 'endpoint_subnet_id': 'endpoint_subnet_id_value'}, 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'azure_services_authentication': {'tenant_id': 'tenant_id_value', 'application_id': 'application_id_value'}, 'state': 1, 'endpoint': 'endpoint_value', 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'cluster_ca_certificate': 'cluster_ca_certificate_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'managed_resources': {'network_security_group_id': 'network_security_group_id_value', 'control_plane_application_security_group_id': 'control_plane_application_security_group_id_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}} + # 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 = azure_service.CreateAzureClusterRequest.meta.fields["azure_cluster"] + + 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["azure_cluster"].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["azure_cluster"][field])): + del request_init["azure_cluster"][field][i][subfield] + else: + del request_init["azure_cluster"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_azure_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_azure_cluster_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_create_azure_cluster") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_create_azure_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.CreateAzureClusterRequest.pb(azure_service.CreateAzureClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = azure_service.CreateAzureClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_azure_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_azure_cluster_rest_bad_request(request_type=azure_service.UpdateAzureClusterRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'azure_cluster': {'name': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_azure_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.UpdateAzureClusterRequest, + dict, +]) +def test_update_azure_cluster_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'azure_cluster': {'name': 'projects/sample1/locations/sample2/azureClusters/sample3'}} + request_init["azure_cluster"] = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3', 'description': 'description_value', 'azure_region': 'azure_region_value', 'resource_group_id': 'resource_group_id_value', 'azure_client': 'azure_client_value', 'networking': {'virtual_network_id': 'virtual_network_id_value', 'pod_address_cidr_blocks': ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'], 'service_address_cidr_blocks': ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'], 'service_load_balancer_subnet_id': 'service_load_balancer_subnet_id_value'}, 'control_plane': {'version': 'version_value', 'subnet_id': 'subnet_id_value', 'vm_size': 'vm_size_value', 'ssh_config': {'authorized_key': 'authorized_key_value'}, 'root_volume': {'size_gib': 844}, 'main_volume': {}, 'database_encryption': {'key_id': 'key_id_value'}, 'proxy_config': {'resource_group_id': 'resource_group_id_value', 'secret_id': 'secret_id_value'}, 'config_encryption': {'key_id': 'key_id_value', 'public_key': 'public_key_value'}, 'tags': {}, 'replica_placements': [{'subnet_id': 'subnet_id_value', 'azure_availability_zone': 'azure_availability_zone_value'}], 'endpoint_subnet_id': 'endpoint_subnet_id_value'}, 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'azure_services_authentication': {'tenant_id': 'tenant_id_value', 'application_id': 'application_id_value'}, 'state': 1, 'endpoint': 'endpoint_value', 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'cluster_ca_certificate': 'cluster_ca_certificate_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'managed_resources': {'network_security_group_id': 'network_security_group_id_value', 'control_plane_application_security_group_id': 'control_plane_application_security_group_id_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}} + # 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 = azure_service.UpdateAzureClusterRequest.meta.fields["azure_cluster"] + + 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["azure_cluster"].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["azure_cluster"][field])): + del request_init["azure_cluster"][field][i][subfield] + else: + del request_init["azure_cluster"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_azure_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_azure_cluster_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_update_azure_cluster") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_update_azure_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.UpdateAzureClusterRequest.pb(azure_service.UpdateAzureClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = azure_service.UpdateAzureClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_azure_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_azure_cluster_rest_bad_request(request_type=azure_service.GetAzureClusterRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_azure_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureClusterRequest, + dict, +]) +def test_get_azure_cluster_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/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 = azure_resources.AzureCluster( + name='name_value', + description='description_value', + azure_region='azure_region_value', + resource_group_id='resource_group_id_value', + azure_client='azure_client_value', + state=azure_resources.AzureCluster.State.PROVISIONING, + endpoint='endpoint_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + cluster_ca_certificate='cluster_ca_certificate_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_resources.AzureCluster.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_azure_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureCluster) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.azure_region == 'azure_region_value' + assert response.resource_group_id == 'resource_group_id_value' + assert response.azure_client == 'azure_client_value' + assert response.state == azure_resources.AzureCluster.State.PROVISIONING + assert response.endpoint == 'endpoint_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_azure_cluster_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_cluster") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.GetAzureClusterRequest.pb(azure_service.GetAzureClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_resources.AzureCluster.to_json(azure_resources.AzureCluster()) + req.return_value.content = return_value + + request = azure_service.GetAzureClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_resources.AzureCluster() + + client.get_azure_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_azure_clusters_rest_bad_request(request_type=azure_service.ListAzureClustersRequest): + client = AzureClustersClient( + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_azure_clusters(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.ListAzureClustersRequest, + dict, +]) +def test_list_azure_clusters_rest_call_success(request_type): + client = AzureClustersClient( + 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 = azure_service.ListAzureClustersResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_service.ListAzureClustersResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_azure_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAzureClustersPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_azure_clusters_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_list_azure_clusters") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_list_azure_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.ListAzureClustersRequest.pb(azure_service.ListAzureClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_service.ListAzureClustersResponse.to_json(azure_service.ListAzureClustersResponse()) + req.return_value.content = return_value + + request = azure_service.ListAzureClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_service.ListAzureClustersResponse() + + client.list_azure_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_azure_cluster_rest_bad_request(request_type=azure_service.DeleteAzureClusterRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_azure_cluster(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.DeleteAzureClusterRequest, + dict, +]) +def test_delete_azure_cluster_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_azure_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_azure_cluster_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_delete_azure_cluster") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_delete_azure_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.DeleteAzureClusterRequest.pb(azure_service.DeleteAzureClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = azure_service.DeleteAzureClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_azure_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_azure_cluster_agent_token_rest_bad_request(request_type=azure_service.GenerateAzureClusterAgentTokenRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.generate_azure_cluster_agent_token(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GenerateAzureClusterAgentTokenRequest, + dict, +]) +def test_generate_azure_cluster_agent_token_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = azure_service.GenerateAzureClusterAgentTokenResponse( + access_token='access_token_value', + expires_in=1078, + token_type='token_type_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_service.GenerateAzureClusterAgentTokenResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.generate_azure_cluster_agent_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_service.GenerateAzureClusterAgentTokenResponse) + assert response.access_token == 'access_token_value' + assert response.expires_in == 1078 + assert response.token_type == 'token_type_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_azure_cluster_agent_token_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_generate_azure_cluster_agent_token") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_generate_azure_cluster_agent_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.GenerateAzureClusterAgentTokenRequest.pb(azure_service.GenerateAzureClusterAgentTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_service.GenerateAzureClusterAgentTokenResponse.to_json(azure_service.GenerateAzureClusterAgentTokenResponse()) + req.return_value.content = return_value + + request = azure_service.GenerateAzureClusterAgentTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_service.GenerateAzureClusterAgentTokenResponse() + + client.generate_azure_cluster_agent_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_azure_access_token_rest_bad_request(request_type=azure_service.GenerateAzureAccessTokenRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.generate_azure_access_token(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GenerateAzureAccessTokenRequest, + dict, +]) +def test_generate_azure_access_token_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = azure_service.GenerateAzureAccessTokenResponse( + access_token='access_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_service.GenerateAzureAccessTokenResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.generate_azure_access_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_service.GenerateAzureAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_azure_access_token_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_generate_azure_access_token") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_generate_azure_access_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.GenerateAzureAccessTokenRequest.pb(azure_service.GenerateAzureAccessTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_service.GenerateAzureAccessTokenResponse.to_json(azure_service.GenerateAzureAccessTokenResponse()) + req.return_value.content = return_value + + request = azure_service.GenerateAzureAccessTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_service.GenerateAzureAccessTokenResponse() + + client.generate_azure_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_azure_node_pool_rest_bad_request(request_type=azure_service.CreateAzureNodePoolRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_azure_node_pool(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.CreateAzureNodePoolRequest, + dict, +]) +def test_create_azure_node_pool_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/azureClusters/sample3'} + request_init["azure_node_pool"] = {'name': 'name_value', 'version': 'version_value', 'config': {'vm_size': 'vm_size_value', 'root_volume': {'size_gib': 844}, 'tags': {}, 'image_type': 'image_type_value', 'ssh_config': {'authorized_key': 'authorized_key_value'}, 'proxy_config': {'resource_group_id': 'resource_group_id_value', 'secret_id': 'secret_id_value'}, 'config_encryption': {'key_id': 'key_id_value', 'public_key': 'public_key_value'}, 'taints': [{'key': 'key_value', 'value': 'value_value', 'effect': 1}], 'labels': {}}, 'subnet_id': 'subnet_id_value', 'autoscaling': {'min_node_count': 1489, 'max_node_count': 1491}, 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'max_pods_constraint': {'max_pods_per_node': 1798}, 'azure_availability_zone': 'azure_availability_zone_value', 'errors': [{'message': 'message_value'}], 'management': {'auto_repair': True}} + # 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 = azure_service.CreateAzureNodePoolRequest.meta.fields["azure_node_pool"] + + 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["azure_node_pool"].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["azure_node_pool"][field])): + del request_init["azure_node_pool"][field][i][subfield] + else: + del request_init["azure_node_pool"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_azure_node_pool(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_azure_node_pool_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_create_azure_node_pool") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_create_azure_node_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.CreateAzureNodePoolRequest.pb(azure_service.CreateAzureNodePoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = azure_service.CreateAzureNodePoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_azure_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_azure_node_pool_rest_bad_request(request_type=azure_service.UpdateAzureNodePoolRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'azure_node_pool': {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_azure_node_pool(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.UpdateAzureNodePoolRequest, + dict, +]) +def test_update_azure_node_pool_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'azure_node_pool': {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'}} + request_init["azure_node_pool"] = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4', 'version': 'version_value', 'config': {'vm_size': 'vm_size_value', 'root_volume': {'size_gib': 844}, 'tags': {}, 'image_type': 'image_type_value', 'ssh_config': {'authorized_key': 'authorized_key_value'}, 'proxy_config': {'resource_group_id': 'resource_group_id_value', 'secret_id': 'secret_id_value'}, 'config_encryption': {'key_id': 'key_id_value', 'public_key': 'public_key_value'}, 'taints': [{'key': 'key_value', 'value': 'value_value', 'effect': 1}], 'labels': {}}, 'subnet_id': 'subnet_id_value', 'autoscaling': {'min_node_count': 1489, 'max_node_count': 1491}, 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'max_pods_constraint': {'max_pods_per_node': 1798}, 'azure_availability_zone': 'azure_availability_zone_value', 'errors': [{'message': 'message_value'}], 'management': {'auto_repair': True}} + # 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 = azure_service.UpdateAzureNodePoolRequest.meta.fields["azure_node_pool"] + + 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["azure_node_pool"].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["azure_node_pool"][field])): + del request_init["azure_node_pool"][field][i][subfield] + else: + del request_init["azure_node_pool"][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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_azure_node_pool(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_azure_node_pool_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_update_azure_node_pool") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_update_azure_node_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.UpdateAzureNodePoolRequest.pb(azure_service.UpdateAzureNodePoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = azure_service.UpdateAzureNodePoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_azure_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_azure_node_pool_rest_bad_request(request_type=azure_service.GetAzureNodePoolRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_azure_node_pool(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureNodePoolRequest, + dict, +]) +def test_get_azure_node_pool_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = azure_resources.AzureNodePool( + name='name_value', + version='version_value', + subnet_id='subnet_id_value', + state=azure_resources.AzureNodePool.State.PROVISIONING, + uid='uid_value', + reconciling=True, + etag='etag_value', + azure_availability_zone='azure_availability_zone_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_resources.AzureNodePool.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_azure_node_pool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureNodePool) + assert response.name == 'name_value' + assert response.version == 'version_value' + assert response.subnet_id == 'subnet_id_value' + assert response.state == azure_resources.AzureNodePool.State.PROVISIONING + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.azure_availability_zone == 'azure_availability_zone_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_azure_node_pool_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_node_pool") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_node_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.GetAzureNodePoolRequest.pb(azure_service.GetAzureNodePoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_resources.AzureNodePool.to_json(azure_resources.AzureNodePool()) + req.return_value.content = return_value + + request = azure_service.GetAzureNodePoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_resources.AzureNodePool() + + client.get_azure_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_azure_node_pools_rest_bad_request(request_type=azure_service.ListAzureNodePoolsRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_azure_node_pools(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.ListAzureNodePoolsRequest, + dict, +]) +def test_list_azure_node_pools_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/azureClusters/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 = azure_service.ListAzureNodePoolsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_service.ListAzureNodePoolsResponse.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_azure_node_pools(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAzureNodePoolsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_azure_node_pools_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_list_azure_node_pools") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_list_azure_node_pools") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.ListAzureNodePoolsRequest.pb(azure_service.ListAzureNodePoolsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_service.ListAzureNodePoolsResponse.to_json(azure_service.ListAzureNodePoolsResponse()) + req.return_value.content = return_value + + request = azure_service.ListAzureNodePoolsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_service.ListAzureNodePoolsResponse() + + client.list_azure_node_pools(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_azure_node_pool_rest_bad_request(request_type=azure_service.DeleteAzureNodePoolRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_azure_node_pool(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.DeleteAzureNodePoolRequest, + dict, +]) +def test_delete_azure_node_pool_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_azure_node_pool(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_azure_node_pool_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_delete_azure_node_pool") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_delete_azure_node_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.DeleteAzureNodePoolRequest.pb(azure_service.DeleteAzureNodePoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = azure_service.DeleteAzureNodePoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_azure_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_azure_open_id_config_rest_bad_request(request_type=azure_service.GetAzureOpenIdConfigRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_azure_open_id_config(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureOpenIdConfigRequest, + dict, +]) +def test_get_azure_open_id_config_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = azure_resources.AzureOpenIdConfig( + issuer='issuer_value', + jwks_uri='jwks_uri_value', + response_types_supported=['response_types_supported_value'], + subject_types_supported=['subject_types_supported_value'], + id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], + claims_supported=['claims_supported_value'], + grant_types=['grant_types_value'], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_resources.AzureOpenIdConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_azure_open_id_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureOpenIdConfig) + assert response.issuer == 'issuer_value' + assert response.jwks_uri == 'jwks_uri_value' + assert response.response_types_supported == ['response_types_supported_value'] + assert response.subject_types_supported == ['subject_types_supported_value'] + assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] + assert response.claims_supported == ['claims_supported_value'] + assert response.grant_types == ['grant_types_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_azure_open_id_config_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_open_id_config") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_open_id_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.GetAzureOpenIdConfigRequest.pb(azure_service.GetAzureOpenIdConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_resources.AzureOpenIdConfig.to_json(azure_resources.AzureOpenIdConfig()) + req.return_value.content = return_value + + request = azure_service.GetAzureOpenIdConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_resources.AzureOpenIdConfig() + + client.get_azure_open_id_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_azure_json_web_keys_rest_bad_request(request_type=azure_service.GetAzureJsonWebKeysRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_azure_json_web_keys(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureJsonWebKeysRequest, + dict, +]) +def test_get_azure_json_web_keys_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = azure_resources.AzureJsonWebKeys( + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_resources.AzureJsonWebKeys.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_azure_json_web_keys(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureJsonWebKeys) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_azure_json_web_keys_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_json_web_keys") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_json_web_keys") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.GetAzureJsonWebKeysRequest.pb(azure_service.GetAzureJsonWebKeysRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_resources.AzureJsonWebKeys.to_json(azure_resources.AzureJsonWebKeys()) + req.return_value.content = return_value + + request = azure_service.GetAzureJsonWebKeysRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_resources.AzureJsonWebKeys() + + client.get_azure_json_web_keys(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_azure_server_config_rest_bad_request(request_type=azure_service.GetAzureServerConfigRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureServerConfig'} + 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_azure_server_config(request) + + +@pytest.mark.parametrize("request_type", [ + azure_service.GetAzureServerConfigRequest, + dict, +]) +def test_get_azure_server_config_rest_call_success(request_type): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/azureServerConfig'} + 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 = azure_resources.AzureServerConfig( + name='name_value', + supported_azure_regions=['supported_azure_regions_value'], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = azure_resources.AzureServerConfig.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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_azure_server_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, azure_resources.AzureServerConfig) + assert response.name == 'name_value' + assert response.supported_azure_regions == ['supported_azure_regions_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_azure_server_config_rest_interceptors(null_interceptor): + transport = transports.AzureClustersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), + ) + client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_server_config") as post, \ + mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_server_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = azure_service.GetAzureServerConfigRequest.pb(azure_service.GetAzureServerConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = azure_resources.AzureServerConfig.to_json(azure_resources.AzureServerConfig()) + req.return_value.content = return_value + + request = azure_service.GetAzureServerConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = azure_resources.AzureServerConfig() + + client.get_azure_server_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = AzureClustersClient( + 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(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 = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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(request_type=operations_pb2.DeleteOperationRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = AzureClustersClient( + 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(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 = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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(request_type=operations_pb2.GetOperationRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = AzureClustersClient( + 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(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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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(request_type=operations_pb2.ListOperationsRequest): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = AzureClustersClient( + 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(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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_initialize_client_w_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_azure_client_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_client), + '__call__') as call: + client.create_azure_client(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.CreateAzureClientRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_client_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_client), + '__call__') as call: + client.get_azure_client(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureClientRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_azure_clients_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clients), + '__call__') as call: + client.list_azure_clients(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.ListAzureClientsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_azure_client_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_client), + '__call__') as call: + client.delete_azure_client(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.DeleteAzureClientRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_azure_cluster_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_cluster), + '__call__') as call: + client.create_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.CreateAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_azure_cluster_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_cluster), + '__call__') as call: + client.update_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.UpdateAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_cluster_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_cluster), + '__call__') as call: + client.get_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_azure_clusters_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_clusters), + '__call__') as call: + client.list_azure_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.ListAzureClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_azure_cluster_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_cluster), + '__call__') as call: + client.delete_azure_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.DeleteAzureClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_azure_cluster_agent_token_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_cluster_agent_token), + '__call__') as call: + client.generate_azure_cluster_agent_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GenerateAzureClusterAgentTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_azure_access_token_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_azure_access_token), + '__call__') as call: + client.generate_azure_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GenerateAzureAccessTokenRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_azure_node_pool_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_azure_node_pool), + '__call__') as call: + client.create_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.CreateAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_azure_node_pool_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_azure_node_pool), + '__call__') as call: + client.update_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.UpdateAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_node_pool_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_node_pool), + '__call__') as call: + client.get_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_azure_node_pools_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_azure_node_pools), + '__call__') as call: + client.list_azure_node_pools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.ListAzureNodePoolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_azure_node_pool_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_azure_node_pool), + '__call__') as call: + client.delete_azure_node_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.DeleteAzureNodePoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_open_id_config_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_open_id_config), + '__call__') as call: + client.get_azure_open_id_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureOpenIdConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_json_web_keys_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_json_web_keys), + '__call__') as call: + client.get_azure_json_web_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureJsonWebKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_azure_server_config_empty_call_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_azure_server_config), + '__call__') as call: + client.get_azure_server_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = azure_service.GetAzureServerConfigRequest() + + assert args[0] == request_msg + + +def test_azure_clusters_rest_lro_client(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an 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 + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AzureClustersGrpcTransport, + ) + +def test_azure_clusters_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AzureClustersTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_azure_clusters_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.gke_multicloud_v1.services.azure_clusters.transports.AzureClustersTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AzureClustersTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_azure_client', + 'get_azure_client', + 'list_azure_clients', + 'delete_azure_client', + 'create_azure_cluster', + 'update_azure_cluster', + 'get_azure_cluster', + 'list_azure_clusters', + 'delete_azure_cluster', + 'generate_azure_cluster_agent_token', + 'generate_azure_access_token', + 'create_azure_node_pool', + 'update_azure_node_pool', + 'get_azure_node_pool', + 'list_azure_node_pools', + 'delete_azure_node_pool', + 'get_azure_open_id_config', + 'get_azure_json_web_keys', + 'get_azure_server_config', + '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_azure_clusters_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.gke_multicloud_v1.services.azure_clusters.transports.AzureClustersTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AzureClustersTransport( + 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_azure_clusters_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.gke_multicloud_v1.services.azure_clusters.transports.AzureClustersTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AzureClustersTransport() + adc.assert_called_once() + + +def test_azure_clusters_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) + AzureClustersClient() + 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.AzureClustersGrpcTransport, + transports.AzureClustersGrpcAsyncIOTransport, + ], +) +def test_azure_clusters_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.AzureClustersGrpcTransport, + transports.AzureClustersGrpcAsyncIOTransport, + transports.AzureClustersRestTransport, + ], +) +def test_azure_clusters_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.AzureClustersGrpcTransport, grpc_helpers), + (transports.AzureClustersGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_azure_clusters_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( + "gkemulticloud.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="gkemulticloud.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AzureClustersGrpcTransport, transports.AzureClustersGrpcAsyncIOTransport]) +def test_azure_clusters_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_azure_clusters_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.AzureClustersRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_azure_clusters_host_no_port(transport_name): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'gkemulticloud.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://gkemulticloud.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_azure_clusters_host_with_port(transport_name): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'gkemulticloud.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://gkemulticloud.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_azure_clusters_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AzureClustersClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AzureClustersClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_azure_client._session + session2 = client2.transport.create_azure_client._session + assert session1 != session2 + session1 = client1.transport.get_azure_client._session + session2 = client2.transport.get_azure_client._session + assert session1 != session2 + session1 = client1.transport.list_azure_clients._session + session2 = client2.transport.list_azure_clients._session + assert session1 != session2 + session1 = client1.transport.delete_azure_client._session + session2 = client2.transport.delete_azure_client._session + assert session1 != session2 + session1 = client1.transport.create_azure_cluster._session + session2 = client2.transport.create_azure_cluster._session + assert session1 != session2 + session1 = client1.transport.update_azure_cluster._session + session2 = client2.transport.update_azure_cluster._session + assert session1 != session2 + session1 = client1.transport.get_azure_cluster._session + session2 = client2.transport.get_azure_cluster._session + assert session1 != session2 + session1 = client1.transport.list_azure_clusters._session + session2 = client2.transport.list_azure_clusters._session + assert session1 != session2 + session1 = client1.transport.delete_azure_cluster._session + session2 = client2.transport.delete_azure_cluster._session + assert session1 != session2 + session1 = client1.transport.generate_azure_cluster_agent_token._session + session2 = client2.transport.generate_azure_cluster_agent_token._session + assert session1 != session2 + session1 = client1.transport.generate_azure_access_token._session + session2 = client2.transport.generate_azure_access_token._session + assert session1 != session2 + session1 = client1.transport.create_azure_node_pool._session + session2 = client2.transport.create_azure_node_pool._session + assert session1 != session2 + session1 = client1.transport.update_azure_node_pool._session + session2 = client2.transport.update_azure_node_pool._session + assert session1 != session2 + session1 = client1.transport.get_azure_node_pool._session + session2 = client2.transport.get_azure_node_pool._session + assert session1 != session2 + session1 = client1.transport.list_azure_node_pools._session + session2 = client2.transport.list_azure_node_pools._session + assert session1 != session2 + session1 = client1.transport.delete_azure_node_pool._session + session2 = client2.transport.delete_azure_node_pool._session + assert session1 != session2 + session1 = client1.transport.get_azure_open_id_config._session + session2 = client2.transport.get_azure_open_id_config._session + assert session1 != session2 + session1 = client1.transport.get_azure_json_web_keys._session + session2 = client2.transport.get_azure_json_web_keys._session + assert session1 != session2 + session1 = client1.transport.get_azure_server_config._session + session2 = client2.transport.get_azure_server_config._session + assert session1 != session2 +def test_azure_clusters_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AzureClustersGrpcTransport( + 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_azure_clusters_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AzureClustersGrpcAsyncIOTransport( + 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.AzureClustersGrpcTransport, transports.AzureClustersGrpcAsyncIOTransport]) +def test_azure_clusters_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.AzureClustersGrpcTransport, transports.AzureClustersGrpcAsyncIOTransport]) +def test_azure_clusters_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_azure_clusters_grpc_lro_client(): + client = AzureClustersClient( + 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_azure_clusters_grpc_lro_async_client(): + client = AzureClustersAsyncClient( + 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_azure_client_path(): + project = "squid" + location = "clam" + azure_client = "whelk" + expected = "projects/{project}/locations/{location}/azureClients/{azure_client}".format(project=project, location=location, azure_client=azure_client, ) + actual = AzureClustersClient.azure_client_path(project, location, azure_client) + assert expected == actual + + +def test_parse_azure_client_path(): + expected = { + "project": "octopus", + "location": "oyster", + "azure_client": "nudibranch", + } + path = AzureClustersClient.azure_client_path(**expected) + + # Check that the path construction is reversible. + actual = AzureClustersClient.parse_azure_client_path(path) + assert expected == actual + +def test_azure_cluster_path(): + project = "cuttlefish" + location = "mussel" + azure_cluster = "winkle" + expected = "projects/{project}/locations/{location}/azureClusters/{azure_cluster}".format(project=project, location=location, azure_cluster=azure_cluster, ) + actual = AzureClustersClient.azure_cluster_path(project, location, azure_cluster) + assert expected == actual + + +def test_parse_azure_cluster_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "azure_cluster": "abalone", + } + path = AzureClustersClient.azure_cluster_path(**expected) + + # Check that the path construction is reversible. + actual = AzureClustersClient.parse_azure_cluster_path(path) + assert expected == actual + +def test_azure_node_pool_path(): + project = "squid" + location = "clam" + azure_cluster = "whelk" + azure_node_pool = "octopus" + expected = "projects/{project}/locations/{location}/azureClusters/{azure_cluster}/azureNodePools/{azure_node_pool}".format(project=project, location=location, azure_cluster=azure_cluster, azure_node_pool=azure_node_pool, ) + actual = AzureClustersClient.azure_node_pool_path(project, location, azure_cluster, azure_node_pool) + assert expected == actual + + +def test_parse_azure_node_pool_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "azure_cluster": "cuttlefish", + "azure_node_pool": "mussel", + } + path = AzureClustersClient.azure_node_pool_path(**expected) + + # Check that the path construction is reversible. + actual = AzureClustersClient.parse_azure_node_pool_path(path) + assert expected == actual + +def test_azure_server_config_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}/azureServerConfig".format(project=project, location=location, ) + actual = AzureClustersClient.azure_server_config_path(project, location) + assert expected == actual + + +def test_parse_azure_server_config_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AzureClustersClient.azure_server_config_path(**expected) + + # Check that the path construction is reversible. + actual = AzureClustersClient.parse_azure_server_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AzureClustersClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AzureClustersClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AzureClustersClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = AzureClustersClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AzureClustersClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AzureClustersClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AzureClustersClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AzureClustersClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AzureClustersClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = AzureClustersClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AzureClustersClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AzureClustersClient.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 = AzureClustersClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AzureClustersClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AzureClustersClient.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.AzureClustersTransport, '_prep_wrapped_messages') as prep: + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AzureClustersTransport, '_prep_wrapped_messages') as prep: + transport_class = AzureClustersClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = AzureClustersClient( + 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_asyncio"): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AzureClustersClient( + 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 = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AzureClustersClient( + 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 = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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 = AzureClustersClient( + 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_asyncio"): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AzureClustersClient( + 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 = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AzureClustersClient( + 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 = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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 = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AzureClustersClient( + 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 = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AzureClustersClient( + 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 = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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 = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), 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 = AzureClustersClient( + 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 = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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 = AzureClustersClient( + 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 = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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_transport_close_grpc(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AzureClustersAsyncClient( + credentials=async_anonymous_credentials(), + 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_rest(): + client = AzureClustersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "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 = AzureClustersClient( + 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", [ + (AzureClustersClient, transports.AzureClustersGrpcTransport), + (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From 233645aeed5ac9cf08a25cf7d71a16dcd87cc51c Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 9 Jan 2025 01:12:02 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../v1/.coveragerc | 13 - .../google-cloud-gke-multicloud/v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../google-cloud-gke-multicloud/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../gke_multicloud_v1/attached_clusters.rst | 10 - .../docs/gke_multicloud_v1/aws_clusters.rst | 10 - .../docs/gke_multicloud_v1/azure_clusters.rst | 10 - .../v1/docs/gke_multicloud_v1/services_.rst | 8 - .../v1/docs/gke_multicloud_v1/types_.rst | 6 - .../v1/docs/index.rst | 7 - .../google/cloud/gke_multicloud/__init__.py | 299 - .../cloud/gke_multicloud/gapic_version.py | 16 - .../v1/google/cloud/gke_multicloud/py.typed | 2 - .../cloud/gke_multicloud_v1/__init__.py | 300 - .../gke_multicloud_v1/gapic_metadata.json | 726 - .../cloud/gke_multicloud_v1/gapic_version.py | 16 - .../google/cloud/gke_multicloud_v1/py.typed | 2 - .../gke_multicloud_v1/services/__init__.py | 15 - .../services/attached_clusters/__init__.py | 22 - .../attached_clusters/async_client.py | 1691 -- .../services/attached_clusters/client.py | 2028 -- .../services/attached_clusters/pagers.py | 167 - .../attached_clusters/transports/README.rst | 9 - .../attached_clusters/transports/__init__.py | 38 - .../attached_clusters/transports/base.py | 375 - .../attached_clusters/transports/grpc.py | 679 - .../transports/grpc_asyncio.py | 804 - .../attached_clusters/transports/rest.py | 2131 --- .../attached_clusters/transports/rest_base.py | 562 - .../services/aws_clusters/__init__.py | 22 - .../services/aws_clusters/async_client.py | 2561 --- .../services/aws_clusters/client.py | 2903 --- .../services/aws_clusters/pagers.py | 306 - .../aws_clusters/transports/README.rst | 9 - .../aws_clusters/transports/__init__.py | 38 - .../services/aws_clusters/transports/base.py | 509 - .../services/aws_clusters/transports/grpc.py | 881 - .../aws_clusters/transports/grpc_asyncio.py | 1077 -- .../services/aws_clusters/transports/rest.py | 3204 ---- .../aws_clusters/transports/rest_base.py | 834 - .../services/azure_clusters/__init__.py | 22 - .../services/azure_clusters/async_client.py | 3034 --- .../services/azure_clusters/client.py | 3380 ---- .../services/azure_clusters/pagers.py | 445 - .../azure_clusters/transports/README.rst | 9 - .../azure_clusters/transports/__init__.py | 38 - .../azure_clusters/transports/base.py | 569 - .../azure_clusters/transports/grpc.py | 981 - .../azure_clusters/transports/grpc_asyncio.py | 1210 -- .../azure_clusters/transports/rest.py | 3678 ---- .../azure_clusters/transports/rest_base.py | 942 - .../cloud/gke_multicloud_v1/types/__init__.py | 296 - .../types/attached_resources.py | 505 - .../types/attached_service.py | 574 - .../gke_multicloud_v1/types/aws_resources.py | 1424 -- .../gke_multicloud_v1/types/aws_service.py | 850 - .../types/azure_resources.py | 1398 -- .../gke_multicloud_v1/types/azure_service.py | 986 - .../types/common_resources.py | 576 - .../google-cloud-gke-multicloud/v1/mypy.ini | 3 - .../google-cloud-gke-multicloud/v1/noxfile.py | 280 - ..._clusters_create_attached_cluster_async.py | 63 - ...d_clusters_create_attached_cluster_sync.py | 63 - ..._clusters_delete_attached_cluster_async.py | 56 - ...d_clusters_delete_attached_cluster_sync.py | 56 - ...rate_attached_cluster_agent_token_async.py | 55 - ...erate_attached_cluster_agent_token_sync.py | 55 - ...attached_cluster_install_manifest_async.py | 54 - ..._attached_cluster_install_manifest_sync.py | 54 - ...hed_clusters_get_attached_cluster_async.py | 52 - ...ched_clusters_get_attached_cluster_sync.py | 52 - ...usters_get_attached_server_config_async.py | 52 - ...lusters_get_attached_server_config_sync.py | 52 - ..._clusters_import_attached_cluster_async.py | 59 - ...d_clusters_import_attached_cluster_sync.py | 59 - ...d_clusters_list_attached_clusters_async.py | 53 - ...ed_clusters_list_attached_clusters_sync.py | 53 - ..._clusters_update_attached_cluster_async.py | 61 - ...d_clusters_update_attached_cluster_sync.py | 61 - ...d_aws_clusters_create_aws_cluster_async.py | 71 - ...ed_aws_clusters_create_aws_cluster_sync.py | 71 - ...aws_clusters_create_aws_node_pool_async.py | 67 - ..._aws_clusters_create_aws_node_pool_sync.py | 67 - ...d_aws_clusters_delete_aws_cluster_async.py | 56 - ...ed_aws_clusters_delete_aws_cluster_sync.py | 56 - ...aws_clusters_delete_aws_node_pool_async.py | 56 - ..._aws_clusters_delete_aws_node_pool_sync.py | 56 - ...lusters_generate_aws_access_token_async.py | 52 - ...clusters_generate_aws_access_token_sync.py | 52 - ..._generate_aws_cluster_agent_token_async.py | 55 - ...s_generate_aws_cluster_agent_token_sync.py | 55 - ...ated_aws_clusters_get_aws_cluster_async.py | 52 - ...rated_aws_clusters_get_aws_cluster_sync.py | 52 - ...ws_clusters_get_aws_json_web_keys_async.py | 52 - ...aws_clusters_get_aws_json_web_keys_sync.py | 52 - ...ed_aws_clusters_get_aws_node_pool_async.py | 52 - ...ted_aws_clusters_get_aws_node_pool_sync.py | 52 - ...s_clusters_get_aws_open_id_config_async.py | 52 - ...ws_clusters_get_aws_open_id_config_sync.py | 52 - ...ws_clusters_get_aws_server_config_async.py | 52 - ...aws_clusters_get_aws_server_config_sync.py | 52 - ...ed_aws_clusters_list_aws_clusters_async.py | 53 - ...ted_aws_clusters_list_aws_clusters_sync.py | 53 - ..._aws_clusters_list_aws_node_pools_async.py | 53 - ...d_aws_clusters_list_aws_node_pools_sync.py | 53 - ...ers_rollback_aws_node_pool_update_async.py | 56 - ...ters_rollback_aws_node_pool_update_sync.py | 56 - ...d_aws_clusters_update_aws_cluster_async.py | 69 - ...ed_aws_clusters_update_aws_cluster_sync.py | 69 - ...aws_clusters_update_aws_node_pool_async.py | 65 - ..._aws_clusters_update_aws_node_pool_sync.py | 65 - ...zure_clusters_create_azure_client_async.py | 62 - ...azure_clusters_create_azure_client_sync.py | 62 - ...ure_clusters_create_azure_cluster_async.py | 68 - ...zure_clusters_create_azure_cluster_sync.py | 68 - ...e_clusters_create_azure_node_pool_async.py | 66 - ...re_clusters_create_azure_node_pool_sync.py | 66 - ...zure_clusters_delete_azure_client_async.py | 56 - ...azure_clusters_delete_azure_client_sync.py | 56 - ...ure_clusters_delete_azure_cluster_async.py | 56 - ...zure_clusters_delete_azure_cluster_sync.py | 56 - ...e_clusters_delete_azure_node_pool_async.py | 56 - ...re_clusters_delete_azure_node_pool_sync.py | 56 - ...sters_generate_azure_access_token_async.py | 52 - ...usters_generate_azure_access_token_sync.py | 52 - ...enerate_azure_cluster_agent_token_async.py | 55 - ...generate_azure_cluster_agent_token_sync.py | 55 - ...d_azure_clusters_get_azure_client_async.py | 52 - ...ed_azure_clusters_get_azure_client_sync.py | 52 - ..._azure_clusters_get_azure_cluster_async.py | 52 - ...d_azure_clusters_get_azure_cluster_sync.py | 52 - ..._clusters_get_azure_json_web_keys_async.py | 52 - ...e_clusters_get_azure_json_web_keys_sync.py | 52 - ...zure_clusters_get_azure_node_pool_async.py | 52 - ...azure_clusters_get_azure_node_pool_sync.py | 52 - ...clusters_get_azure_open_id_config_async.py | 52 - ..._clusters_get_azure_open_id_config_sync.py | 52 - ..._clusters_get_azure_server_config_async.py | 52 - ...e_clusters_get_azure_server_config_sync.py | 52 - ...azure_clusters_list_azure_clients_async.py | 53 - ..._azure_clusters_list_azure_clients_sync.py | 53 - ...zure_clusters_list_azure_clusters_async.py | 53 - ...azure_clusters_list_azure_clusters_sync.py | 53 - ...re_clusters_list_azure_node_pools_async.py | 53 - ...ure_clusters_list_azure_node_pools_sync.py | 53 - ...ure_clusters_update_azure_cluster_async.py | 66 - ...zure_clusters_update_azure_cluster_sync.py | 66 - ...e_clusters_update_azure_node_pool_async.py | 64 - ...re_clusters_update_azure_node_pool_sync.py | 64 - ...etadata_google.cloud.gkemulticloud.v1.json | 7195 ------- .../fixup_gke_multicloud_v1_keywords.py | 219 - .../google-cloud-gke-multicloud/v1/setup.py | 98 - .../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.13.txt | 6 - .../v1/testing/constraints-3.7.txt | 10 - .../v1/testing/constraints-3.8.txt | 6 - .../v1/testing/constraints-3.9.txt | 6 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/gke_multicloud_v1/__init__.py | 16 - .../test_attached_clusters.py | 8616 --------- .../gke_multicloud_v1/test_aws_clusters.py | 13259 ------------- .../gke_multicloud_v1/test_azure_clusters.py | 15936 ---------------- .../cloud/gke_multicloud/gapic_version.py | 2 +- .../cloud/gke_multicloud_v1/gapic_version.py | 2 +- .../types/attached_resources.py | 2 +- ...etadata_google.cloud.gkemulticloud.v1.json | 2 +- 172 files changed, 4 insertions(+), 94370 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/attached_clusters.rst delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/aws_clusters.rst delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/azure_clusters.rst delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/py.typed delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/async_client.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/client.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/pagers.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/async_client.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/client.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/pagers.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/async_client.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/client.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/pagers.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_resources.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_service.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_resources.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_service.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_resources.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_service.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/common_resources.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/scripts/fixup_gke_multicloud_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_attached_clusters.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_aws_clusters.py delete mode 100644 owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_azure_clusters.py diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/.coveragerc b/owl-bot-staging/google-cloud-gke-multicloud/v1/.coveragerc deleted file mode 100644 index 5e02aeaf7a3a..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/gke_multicloud/__init__.py - google/cloud/gke_multicloud/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/.flake8 b/owl-bot-staging/google-cloud-gke-multicloud/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/MANIFEST.in b/owl-bot-staging/google-cloud-gke-multicloud/v1/MANIFEST.in deleted file mode 100644 index bfb6acf0cc1b..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/gke_multicloud *.py -recursive-include google/cloud/gke_multicloud_v1 *.py diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/README.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/README.rst deleted file mode 100644 index 9819c2326735..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Gke Multicloud 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 Gke Multicloud API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/conf.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/conf.py deleted file mode 100644 index caf1acccc968..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-gke-multicloud 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-multicloud" -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-multicloud-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-multicloud.tex", - u"google-cloud-gke-multicloud 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-multicloud", - u"Google Cloud Gke Multicloud 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-multicloud", - u"google-cloud-gke-multicloud Documentation", - author, - "google-cloud-gke-multicloud", - "GAPIC library for Google Cloud Gke Multicloud API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/attached_clusters.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/attached_clusters.rst deleted file mode 100644 index b5ef09045bc5..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/attached_clusters.rst +++ /dev/null @@ -1,10 +0,0 @@ -AttachedClusters ----------------------------------- - -.. automodule:: google.cloud.gke_multicloud_v1.services.attached_clusters - :members: - :inherited-members: - -.. automodule:: google.cloud.gke_multicloud_v1.services.attached_clusters.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/aws_clusters.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/aws_clusters.rst deleted file mode 100644 index 3c6c464c9735..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/aws_clusters.rst +++ /dev/null @@ -1,10 +0,0 @@ -AwsClusters ------------------------------ - -.. automodule:: google.cloud.gke_multicloud_v1.services.aws_clusters - :members: - :inherited-members: - -.. automodule:: google.cloud.gke_multicloud_v1.services.aws_clusters.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/azure_clusters.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/azure_clusters.rst deleted file mode 100644 index 2ba97619d4ce..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/azure_clusters.rst +++ /dev/null @@ -1,10 +0,0 @@ -AzureClusters -------------------------------- - -.. automodule:: google.cloud.gke_multicloud_v1.services.azure_clusters - :members: - :inherited-members: - -.. automodule:: google.cloud.gke_multicloud_v1.services.azure_clusters.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/services_.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/services_.rst deleted file mode 100644 index 6f2ba1f59ab4..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/services_.rst +++ /dev/null @@ -1,8 +0,0 @@ -Services for Google Cloud Gke Multicloud v1 API -=============================================== -.. toctree:: - :maxdepth: 2 - - attached_clusters - aws_clusters - azure_clusters diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/types_.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/types_.rst deleted file mode 100644 index e98b40dbb745..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/gke_multicloud_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Gke Multicloud v1 API -============================================ - -.. automodule:: google.cloud.gke_multicloud_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/index.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/index.rst deleted file mode 100644 index 306bfc21e2b0..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - gke_multicloud_v1/services_ - gke_multicloud_v1/types_ diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/__init__.py deleted file mode 100644 index 08a8a2fd4d39..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/__init__.py +++ /dev/null @@ -1,299 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.gke_multicloud import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.gke_multicloud_v1.services.attached_clusters.client import AttachedClustersClient -from google.cloud.gke_multicloud_v1.services.attached_clusters.async_client import AttachedClustersAsyncClient -from google.cloud.gke_multicloud_v1.services.aws_clusters.client import AwsClustersClient -from google.cloud.gke_multicloud_v1.services.aws_clusters.async_client import AwsClustersAsyncClient -from google.cloud.gke_multicloud_v1.services.azure_clusters.client import AzureClustersClient -from google.cloud.gke_multicloud_v1.services.azure_clusters.async_client import AzureClustersAsyncClient - -from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedCluster -from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedClusterError -from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedClusterGroup -from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedClustersAuthorization -from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedClusterUser -from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedOidcConfig -from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedPlatformVersionInfo -from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedProxyConfig -from google.cloud.gke_multicloud_v1.types.attached_resources import AttachedServerConfig -from google.cloud.gke_multicloud_v1.types.attached_resources import KubernetesSecret -from google.cloud.gke_multicloud_v1.types.attached_service import CreateAttachedClusterRequest -from google.cloud.gke_multicloud_v1.types.attached_service import DeleteAttachedClusterRequest -from google.cloud.gke_multicloud_v1.types.attached_service import GenerateAttachedClusterAgentTokenRequest -from google.cloud.gke_multicloud_v1.types.attached_service import GenerateAttachedClusterAgentTokenResponse -from google.cloud.gke_multicloud_v1.types.attached_service import GenerateAttachedClusterInstallManifestRequest -from google.cloud.gke_multicloud_v1.types.attached_service import GenerateAttachedClusterInstallManifestResponse -from google.cloud.gke_multicloud_v1.types.attached_service import GetAttachedClusterRequest -from google.cloud.gke_multicloud_v1.types.attached_service import GetAttachedServerConfigRequest -from google.cloud.gke_multicloud_v1.types.attached_service import ImportAttachedClusterRequest -from google.cloud.gke_multicloud_v1.types.attached_service import ListAttachedClustersRequest -from google.cloud.gke_multicloud_v1.types.attached_service import ListAttachedClustersResponse -from google.cloud.gke_multicloud_v1.types.attached_service import UpdateAttachedClusterRequest -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsAuthorization -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsAutoscalingGroupMetricsCollection -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsCluster -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsClusterError -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsClusterGroup -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsClusterNetworking -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsClusterUser -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsConfigEncryption -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsControlPlane -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsDatabaseEncryption -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsInstancePlacement -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsJsonWebKeys -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsK8sVersionInfo -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsNodeConfig -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsNodeManagement -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsNodePool -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsNodePoolAutoscaling -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsNodePoolError -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsOpenIdConfig -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsProxyConfig -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsServerConfig -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsServicesAuthentication -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsSshConfig -from google.cloud.gke_multicloud_v1.types.aws_resources import AwsVolumeTemplate -from google.cloud.gke_multicloud_v1.types.aws_resources import SpotConfig -from google.cloud.gke_multicloud_v1.types.aws_resources import SurgeSettings -from google.cloud.gke_multicloud_v1.types.aws_resources import UpdateSettings -from google.cloud.gke_multicloud_v1.types.aws_service import CreateAwsClusterRequest -from google.cloud.gke_multicloud_v1.types.aws_service import CreateAwsNodePoolRequest -from google.cloud.gke_multicloud_v1.types.aws_service import DeleteAwsClusterRequest -from google.cloud.gke_multicloud_v1.types.aws_service import DeleteAwsNodePoolRequest -from google.cloud.gke_multicloud_v1.types.aws_service import GenerateAwsAccessTokenRequest -from google.cloud.gke_multicloud_v1.types.aws_service import GenerateAwsAccessTokenResponse -from google.cloud.gke_multicloud_v1.types.aws_service import GenerateAwsClusterAgentTokenRequest -from google.cloud.gke_multicloud_v1.types.aws_service import GenerateAwsClusterAgentTokenResponse -from google.cloud.gke_multicloud_v1.types.aws_service import GetAwsClusterRequest -from google.cloud.gke_multicloud_v1.types.aws_service import GetAwsJsonWebKeysRequest -from google.cloud.gke_multicloud_v1.types.aws_service import GetAwsNodePoolRequest -from google.cloud.gke_multicloud_v1.types.aws_service import GetAwsOpenIdConfigRequest -from google.cloud.gke_multicloud_v1.types.aws_service import GetAwsServerConfigRequest -from google.cloud.gke_multicloud_v1.types.aws_service import ListAwsClustersRequest -from google.cloud.gke_multicloud_v1.types.aws_service import ListAwsClustersResponse -from google.cloud.gke_multicloud_v1.types.aws_service import ListAwsNodePoolsRequest -from google.cloud.gke_multicloud_v1.types.aws_service import ListAwsNodePoolsResponse -from google.cloud.gke_multicloud_v1.types.aws_service import RollbackAwsNodePoolUpdateRequest -from google.cloud.gke_multicloud_v1.types.aws_service import UpdateAwsClusterRequest -from google.cloud.gke_multicloud_v1.types.aws_service import UpdateAwsNodePoolRequest -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureAuthorization -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClient -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureCluster -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClusterError -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClusterGroup -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClusterNetworking -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClusterResources -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureClusterUser -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureConfigEncryption -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureControlPlane -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureDatabaseEncryption -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureDiskTemplate -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureJsonWebKeys -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureK8sVersionInfo -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureNodeConfig -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureNodeManagement -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureNodePool -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureNodePoolAutoscaling -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureNodePoolError -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureOpenIdConfig -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureProxyConfig -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureServerConfig -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureServicesAuthentication -from google.cloud.gke_multicloud_v1.types.azure_resources import AzureSshConfig -from google.cloud.gke_multicloud_v1.types.azure_resources import ReplicaPlacement -from google.cloud.gke_multicloud_v1.types.azure_service import CreateAzureClientRequest -from google.cloud.gke_multicloud_v1.types.azure_service import CreateAzureClusterRequest -from google.cloud.gke_multicloud_v1.types.azure_service import CreateAzureNodePoolRequest -from google.cloud.gke_multicloud_v1.types.azure_service import DeleteAzureClientRequest -from google.cloud.gke_multicloud_v1.types.azure_service import DeleteAzureClusterRequest -from google.cloud.gke_multicloud_v1.types.azure_service import DeleteAzureNodePoolRequest -from google.cloud.gke_multicloud_v1.types.azure_service import GenerateAzureAccessTokenRequest -from google.cloud.gke_multicloud_v1.types.azure_service import GenerateAzureAccessTokenResponse -from google.cloud.gke_multicloud_v1.types.azure_service import GenerateAzureClusterAgentTokenRequest -from google.cloud.gke_multicloud_v1.types.azure_service import GenerateAzureClusterAgentTokenResponse -from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureClientRequest -from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureClusterRequest -from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureJsonWebKeysRequest -from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureNodePoolRequest -from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureOpenIdConfigRequest -from google.cloud.gke_multicloud_v1.types.azure_service import GetAzureServerConfigRequest -from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureClientsRequest -from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureClientsResponse -from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureClustersRequest -from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureClustersResponse -from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureNodePoolsRequest -from google.cloud.gke_multicloud_v1.types.azure_service import ListAzureNodePoolsResponse -from google.cloud.gke_multicloud_v1.types.azure_service import UpdateAzureClusterRequest -from google.cloud.gke_multicloud_v1.types.azure_service import UpdateAzureNodePoolRequest -from google.cloud.gke_multicloud_v1.types.common_resources import BinaryAuthorization -from google.cloud.gke_multicloud_v1.types.common_resources import CloudMonitoringConfig -from google.cloud.gke_multicloud_v1.types.common_resources import Fleet -from google.cloud.gke_multicloud_v1.types.common_resources import Jwk -from google.cloud.gke_multicloud_v1.types.common_resources import LoggingComponentConfig -from google.cloud.gke_multicloud_v1.types.common_resources import LoggingConfig -from google.cloud.gke_multicloud_v1.types.common_resources import ManagedPrometheusConfig -from google.cloud.gke_multicloud_v1.types.common_resources import MaxPodsConstraint -from google.cloud.gke_multicloud_v1.types.common_resources import MonitoringConfig -from google.cloud.gke_multicloud_v1.types.common_resources import NodeKubeletConfig -from google.cloud.gke_multicloud_v1.types.common_resources import NodeTaint -from google.cloud.gke_multicloud_v1.types.common_resources import OperationMetadata -from google.cloud.gke_multicloud_v1.types.common_resources import SecurityPostureConfig -from google.cloud.gke_multicloud_v1.types.common_resources import WorkloadIdentityConfig - -__all__ = ('AttachedClustersClient', - 'AttachedClustersAsyncClient', - 'AwsClustersClient', - 'AwsClustersAsyncClient', - 'AzureClustersClient', - 'AzureClustersAsyncClient', - 'AttachedCluster', - 'AttachedClusterError', - 'AttachedClusterGroup', - 'AttachedClustersAuthorization', - 'AttachedClusterUser', - 'AttachedOidcConfig', - 'AttachedPlatformVersionInfo', - 'AttachedProxyConfig', - 'AttachedServerConfig', - 'KubernetesSecret', - 'CreateAttachedClusterRequest', - 'DeleteAttachedClusterRequest', - 'GenerateAttachedClusterAgentTokenRequest', - 'GenerateAttachedClusterAgentTokenResponse', - 'GenerateAttachedClusterInstallManifestRequest', - 'GenerateAttachedClusterInstallManifestResponse', - 'GetAttachedClusterRequest', - 'GetAttachedServerConfigRequest', - 'ImportAttachedClusterRequest', - 'ListAttachedClustersRequest', - 'ListAttachedClustersResponse', - 'UpdateAttachedClusterRequest', - 'AwsAuthorization', - 'AwsAutoscalingGroupMetricsCollection', - 'AwsCluster', - 'AwsClusterError', - 'AwsClusterGroup', - 'AwsClusterNetworking', - 'AwsClusterUser', - 'AwsConfigEncryption', - 'AwsControlPlane', - 'AwsDatabaseEncryption', - 'AwsInstancePlacement', - 'AwsJsonWebKeys', - 'AwsK8sVersionInfo', - 'AwsNodeConfig', - 'AwsNodeManagement', - 'AwsNodePool', - 'AwsNodePoolAutoscaling', - 'AwsNodePoolError', - 'AwsOpenIdConfig', - 'AwsProxyConfig', - 'AwsServerConfig', - 'AwsServicesAuthentication', - 'AwsSshConfig', - 'AwsVolumeTemplate', - 'SpotConfig', - 'SurgeSettings', - 'UpdateSettings', - 'CreateAwsClusterRequest', - 'CreateAwsNodePoolRequest', - 'DeleteAwsClusterRequest', - 'DeleteAwsNodePoolRequest', - 'GenerateAwsAccessTokenRequest', - 'GenerateAwsAccessTokenResponse', - 'GenerateAwsClusterAgentTokenRequest', - 'GenerateAwsClusterAgentTokenResponse', - 'GetAwsClusterRequest', - 'GetAwsJsonWebKeysRequest', - 'GetAwsNodePoolRequest', - 'GetAwsOpenIdConfigRequest', - 'GetAwsServerConfigRequest', - 'ListAwsClustersRequest', - 'ListAwsClustersResponse', - 'ListAwsNodePoolsRequest', - 'ListAwsNodePoolsResponse', - 'RollbackAwsNodePoolUpdateRequest', - 'UpdateAwsClusterRequest', - 'UpdateAwsNodePoolRequest', - 'AzureAuthorization', - 'AzureClient', - 'AzureCluster', - 'AzureClusterError', - 'AzureClusterGroup', - 'AzureClusterNetworking', - 'AzureClusterResources', - 'AzureClusterUser', - 'AzureConfigEncryption', - 'AzureControlPlane', - 'AzureDatabaseEncryption', - 'AzureDiskTemplate', - 'AzureJsonWebKeys', - 'AzureK8sVersionInfo', - 'AzureNodeConfig', - 'AzureNodeManagement', - 'AzureNodePool', - 'AzureNodePoolAutoscaling', - 'AzureNodePoolError', - 'AzureOpenIdConfig', - 'AzureProxyConfig', - 'AzureServerConfig', - 'AzureServicesAuthentication', - 'AzureSshConfig', - 'ReplicaPlacement', - 'CreateAzureClientRequest', - 'CreateAzureClusterRequest', - 'CreateAzureNodePoolRequest', - 'DeleteAzureClientRequest', - 'DeleteAzureClusterRequest', - 'DeleteAzureNodePoolRequest', - 'GenerateAzureAccessTokenRequest', - 'GenerateAzureAccessTokenResponse', - 'GenerateAzureClusterAgentTokenRequest', - 'GenerateAzureClusterAgentTokenResponse', - 'GetAzureClientRequest', - 'GetAzureClusterRequest', - 'GetAzureJsonWebKeysRequest', - 'GetAzureNodePoolRequest', - 'GetAzureOpenIdConfigRequest', - 'GetAzureServerConfigRequest', - 'ListAzureClientsRequest', - 'ListAzureClientsResponse', - 'ListAzureClustersRequest', - 'ListAzureClustersResponse', - 'ListAzureNodePoolsRequest', - 'ListAzureNodePoolsResponse', - 'UpdateAzureClusterRequest', - 'UpdateAzureNodePoolRequest', - 'BinaryAuthorization', - 'CloudMonitoringConfig', - 'Fleet', - 'Jwk', - 'LoggingComponentConfig', - 'LoggingConfig', - 'ManagedPrometheusConfig', - 'MaxPodsConstraint', - 'MonitoringConfig', - 'NodeKubeletConfig', - 'NodeTaint', - 'OperationMetadata', - 'SecurityPostureConfig', - 'WorkloadIdentityConfig', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/gapic_version.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/py.typed b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/py.typed deleted file mode 100644 index 53546ad8d1e7..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-gke-multicloud package uses inline types. diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/__init__.py deleted file mode 100644 index e62d46fa024e..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/__init__.py +++ /dev/null @@ -1,300 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.gke_multicloud_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.attached_clusters import AttachedClustersClient -from .services.attached_clusters import AttachedClustersAsyncClient -from .services.aws_clusters import AwsClustersClient -from .services.aws_clusters import AwsClustersAsyncClient -from .services.azure_clusters import AzureClustersClient -from .services.azure_clusters import AzureClustersAsyncClient - -from .types.attached_resources import AttachedCluster -from .types.attached_resources import AttachedClusterError -from .types.attached_resources import AttachedClusterGroup -from .types.attached_resources import AttachedClustersAuthorization -from .types.attached_resources import AttachedClusterUser -from .types.attached_resources import AttachedOidcConfig -from .types.attached_resources import AttachedPlatformVersionInfo -from .types.attached_resources import AttachedProxyConfig -from .types.attached_resources import AttachedServerConfig -from .types.attached_resources import KubernetesSecret -from .types.attached_service import CreateAttachedClusterRequest -from .types.attached_service import DeleteAttachedClusterRequest -from .types.attached_service import GenerateAttachedClusterAgentTokenRequest -from .types.attached_service import GenerateAttachedClusterAgentTokenResponse -from .types.attached_service import GenerateAttachedClusterInstallManifestRequest -from .types.attached_service import GenerateAttachedClusterInstallManifestResponse -from .types.attached_service import GetAttachedClusterRequest -from .types.attached_service import GetAttachedServerConfigRequest -from .types.attached_service import ImportAttachedClusterRequest -from .types.attached_service import ListAttachedClustersRequest -from .types.attached_service import ListAttachedClustersResponse -from .types.attached_service import UpdateAttachedClusterRequest -from .types.aws_resources import AwsAuthorization -from .types.aws_resources import AwsAutoscalingGroupMetricsCollection -from .types.aws_resources import AwsCluster -from .types.aws_resources import AwsClusterError -from .types.aws_resources import AwsClusterGroup -from .types.aws_resources import AwsClusterNetworking -from .types.aws_resources import AwsClusterUser -from .types.aws_resources import AwsConfigEncryption -from .types.aws_resources import AwsControlPlane -from .types.aws_resources import AwsDatabaseEncryption -from .types.aws_resources import AwsInstancePlacement -from .types.aws_resources import AwsJsonWebKeys -from .types.aws_resources import AwsK8sVersionInfo -from .types.aws_resources import AwsNodeConfig -from .types.aws_resources import AwsNodeManagement -from .types.aws_resources import AwsNodePool -from .types.aws_resources import AwsNodePoolAutoscaling -from .types.aws_resources import AwsNodePoolError -from .types.aws_resources import AwsOpenIdConfig -from .types.aws_resources import AwsProxyConfig -from .types.aws_resources import AwsServerConfig -from .types.aws_resources import AwsServicesAuthentication -from .types.aws_resources import AwsSshConfig -from .types.aws_resources import AwsVolumeTemplate -from .types.aws_resources import SpotConfig -from .types.aws_resources import SurgeSettings -from .types.aws_resources import UpdateSettings -from .types.aws_service import CreateAwsClusterRequest -from .types.aws_service import CreateAwsNodePoolRequest -from .types.aws_service import DeleteAwsClusterRequest -from .types.aws_service import DeleteAwsNodePoolRequest -from .types.aws_service import GenerateAwsAccessTokenRequest -from .types.aws_service import GenerateAwsAccessTokenResponse -from .types.aws_service import GenerateAwsClusterAgentTokenRequest -from .types.aws_service import GenerateAwsClusterAgentTokenResponse -from .types.aws_service import GetAwsClusterRequest -from .types.aws_service import GetAwsJsonWebKeysRequest -from .types.aws_service import GetAwsNodePoolRequest -from .types.aws_service import GetAwsOpenIdConfigRequest -from .types.aws_service import GetAwsServerConfigRequest -from .types.aws_service import ListAwsClustersRequest -from .types.aws_service import ListAwsClustersResponse -from .types.aws_service import ListAwsNodePoolsRequest -from .types.aws_service import ListAwsNodePoolsResponse -from .types.aws_service import RollbackAwsNodePoolUpdateRequest -from .types.aws_service import UpdateAwsClusterRequest -from .types.aws_service import UpdateAwsNodePoolRequest -from .types.azure_resources import AzureAuthorization -from .types.azure_resources import AzureClient -from .types.azure_resources import AzureCluster -from .types.azure_resources import AzureClusterError -from .types.azure_resources import AzureClusterGroup -from .types.azure_resources import AzureClusterNetworking -from .types.azure_resources import AzureClusterResources -from .types.azure_resources import AzureClusterUser -from .types.azure_resources import AzureConfigEncryption -from .types.azure_resources import AzureControlPlane -from .types.azure_resources import AzureDatabaseEncryption -from .types.azure_resources import AzureDiskTemplate -from .types.azure_resources import AzureJsonWebKeys -from .types.azure_resources import AzureK8sVersionInfo -from .types.azure_resources import AzureNodeConfig -from .types.azure_resources import AzureNodeManagement -from .types.azure_resources import AzureNodePool -from .types.azure_resources import AzureNodePoolAutoscaling -from .types.azure_resources import AzureNodePoolError -from .types.azure_resources import AzureOpenIdConfig -from .types.azure_resources import AzureProxyConfig -from .types.azure_resources import AzureServerConfig -from .types.azure_resources import AzureServicesAuthentication -from .types.azure_resources import AzureSshConfig -from .types.azure_resources import ReplicaPlacement -from .types.azure_service import CreateAzureClientRequest -from .types.azure_service import CreateAzureClusterRequest -from .types.azure_service import CreateAzureNodePoolRequest -from .types.azure_service import DeleteAzureClientRequest -from .types.azure_service import DeleteAzureClusterRequest -from .types.azure_service import DeleteAzureNodePoolRequest -from .types.azure_service import GenerateAzureAccessTokenRequest -from .types.azure_service import GenerateAzureAccessTokenResponse -from .types.azure_service import GenerateAzureClusterAgentTokenRequest -from .types.azure_service import GenerateAzureClusterAgentTokenResponse -from .types.azure_service import GetAzureClientRequest -from .types.azure_service import GetAzureClusterRequest -from .types.azure_service import GetAzureJsonWebKeysRequest -from .types.azure_service import GetAzureNodePoolRequest -from .types.azure_service import GetAzureOpenIdConfigRequest -from .types.azure_service import GetAzureServerConfigRequest -from .types.azure_service import ListAzureClientsRequest -from .types.azure_service import ListAzureClientsResponse -from .types.azure_service import ListAzureClustersRequest -from .types.azure_service import ListAzureClustersResponse -from .types.azure_service import ListAzureNodePoolsRequest -from .types.azure_service import ListAzureNodePoolsResponse -from .types.azure_service import UpdateAzureClusterRequest -from .types.azure_service import UpdateAzureNodePoolRequest -from .types.common_resources import BinaryAuthorization -from .types.common_resources import CloudMonitoringConfig -from .types.common_resources import Fleet -from .types.common_resources import Jwk -from .types.common_resources import LoggingComponentConfig -from .types.common_resources import LoggingConfig -from .types.common_resources import ManagedPrometheusConfig -from .types.common_resources import MaxPodsConstraint -from .types.common_resources import MonitoringConfig -from .types.common_resources import NodeKubeletConfig -from .types.common_resources import NodeTaint -from .types.common_resources import OperationMetadata -from .types.common_resources import SecurityPostureConfig -from .types.common_resources import WorkloadIdentityConfig - -__all__ = ( - 'AttachedClustersAsyncClient', - 'AwsClustersAsyncClient', - 'AzureClustersAsyncClient', -'AttachedCluster', -'AttachedClusterError', -'AttachedClusterGroup', -'AttachedClusterUser', -'AttachedClustersAuthorization', -'AttachedClustersClient', -'AttachedOidcConfig', -'AttachedPlatformVersionInfo', -'AttachedProxyConfig', -'AttachedServerConfig', -'AwsAuthorization', -'AwsAutoscalingGroupMetricsCollection', -'AwsCluster', -'AwsClusterError', -'AwsClusterGroup', -'AwsClusterNetworking', -'AwsClusterUser', -'AwsClustersClient', -'AwsConfigEncryption', -'AwsControlPlane', -'AwsDatabaseEncryption', -'AwsInstancePlacement', -'AwsJsonWebKeys', -'AwsK8sVersionInfo', -'AwsNodeConfig', -'AwsNodeManagement', -'AwsNodePool', -'AwsNodePoolAutoscaling', -'AwsNodePoolError', -'AwsOpenIdConfig', -'AwsProxyConfig', -'AwsServerConfig', -'AwsServicesAuthentication', -'AwsSshConfig', -'AwsVolumeTemplate', -'AzureAuthorization', -'AzureClient', -'AzureCluster', -'AzureClusterError', -'AzureClusterGroup', -'AzureClusterNetworking', -'AzureClusterResources', -'AzureClusterUser', -'AzureClustersClient', -'AzureConfigEncryption', -'AzureControlPlane', -'AzureDatabaseEncryption', -'AzureDiskTemplate', -'AzureJsonWebKeys', -'AzureK8sVersionInfo', -'AzureNodeConfig', -'AzureNodeManagement', -'AzureNodePool', -'AzureNodePoolAutoscaling', -'AzureNodePoolError', -'AzureOpenIdConfig', -'AzureProxyConfig', -'AzureServerConfig', -'AzureServicesAuthentication', -'AzureSshConfig', -'BinaryAuthorization', -'CloudMonitoringConfig', -'CreateAttachedClusterRequest', -'CreateAwsClusterRequest', -'CreateAwsNodePoolRequest', -'CreateAzureClientRequest', -'CreateAzureClusterRequest', -'CreateAzureNodePoolRequest', -'DeleteAttachedClusterRequest', -'DeleteAwsClusterRequest', -'DeleteAwsNodePoolRequest', -'DeleteAzureClientRequest', -'DeleteAzureClusterRequest', -'DeleteAzureNodePoolRequest', -'Fleet', -'GenerateAttachedClusterAgentTokenRequest', -'GenerateAttachedClusterAgentTokenResponse', -'GenerateAttachedClusterInstallManifestRequest', -'GenerateAttachedClusterInstallManifestResponse', -'GenerateAwsAccessTokenRequest', -'GenerateAwsAccessTokenResponse', -'GenerateAwsClusterAgentTokenRequest', -'GenerateAwsClusterAgentTokenResponse', -'GenerateAzureAccessTokenRequest', -'GenerateAzureAccessTokenResponse', -'GenerateAzureClusterAgentTokenRequest', -'GenerateAzureClusterAgentTokenResponse', -'GetAttachedClusterRequest', -'GetAttachedServerConfigRequest', -'GetAwsClusterRequest', -'GetAwsJsonWebKeysRequest', -'GetAwsNodePoolRequest', -'GetAwsOpenIdConfigRequest', -'GetAwsServerConfigRequest', -'GetAzureClientRequest', -'GetAzureClusterRequest', -'GetAzureJsonWebKeysRequest', -'GetAzureNodePoolRequest', -'GetAzureOpenIdConfigRequest', -'GetAzureServerConfigRequest', -'ImportAttachedClusterRequest', -'Jwk', -'KubernetesSecret', -'ListAttachedClustersRequest', -'ListAttachedClustersResponse', -'ListAwsClustersRequest', -'ListAwsClustersResponse', -'ListAwsNodePoolsRequest', -'ListAwsNodePoolsResponse', -'ListAzureClientsRequest', -'ListAzureClientsResponse', -'ListAzureClustersRequest', -'ListAzureClustersResponse', -'ListAzureNodePoolsRequest', -'ListAzureNodePoolsResponse', -'LoggingComponentConfig', -'LoggingConfig', -'ManagedPrometheusConfig', -'MaxPodsConstraint', -'MonitoringConfig', -'NodeKubeletConfig', -'NodeTaint', -'OperationMetadata', -'ReplicaPlacement', -'RollbackAwsNodePoolUpdateRequest', -'SecurityPostureConfig', -'SpotConfig', -'SurgeSettings', -'UpdateAttachedClusterRequest', -'UpdateAwsClusterRequest', -'UpdateAwsNodePoolRequest', -'UpdateAzureClusterRequest', -'UpdateAzureNodePoolRequest', -'UpdateSettings', -'WorkloadIdentityConfig', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_metadata.json deleted file mode 100644 index 544cf3260044..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_metadata.json +++ /dev/null @@ -1,726 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.gke_multicloud_v1", - "protoPackage": "google.cloud.gkemulticloud.v1", - "schema": "1.0", - "services": { - "AttachedClusters": { - "clients": { - "grpc": { - "libraryClient": "AttachedClustersClient", - "rpcs": { - "CreateAttachedCluster": { - "methods": [ - "create_attached_cluster" - ] - }, - "DeleteAttachedCluster": { - "methods": [ - "delete_attached_cluster" - ] - }, - "GenerateAttachedClusterAgentToken": { - "methods": [ - "generate_attached_cluster_agent_token" - ] - }, - "GenerateAttachedClusterInstallManifest": { - "methods": [ - "generate_attached_cluster_install_manifest" - ] - }, - "GetAttachedCluster": { - "methods": [ - "get_attached_cluster" - ] - }, - "GetAttachedServerConfig": { - "methods": [ - "get_attached_server_config" - ] - }, - "ImportAttachedCluster": { - "methods": [ - "import_attached_cluster" - ] - }, - "ListAttachedClusters": { - "methods": [ - "list_attached_clusters" - ] - }, - "UpdateAttachedCluster": { - "methods": [ - "update_attached_cluster" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AttachedClustersAsyncClient", - "rpcs": { - "CreateAttachedCluster": { - "methods": [ - "create_attached_cluster" - ] - }, - "DeleteAttachedCluster": { - "methods": [ - "delete_attached_cluster" - ] - }, - "GenerateAttachedClusterAgentToken": { - "methods": [ - "generate_attached_cluster_agent_token" - ] - }, - "GenerateAttachedClusterInstallManifest": { - "methods": [ - "generate_attached_cluster_install_manifest" - ] - }, - "GetAttachedCluster": { - "methods": [ - "get_attached_cluster" - ] - }, - "GetAttachedServerConfig": { - "methods": [ - "get_attached_server_config" - ] - }, - "ImportAttachedCluster": { - "methods": [ - "import_attached_cluster" - ] - }, - "ListAttachedClusters": { - "methods": [ - "list_attached_clusters" - ] - }, - "UpdateAttachedCluster": { - "methods": [ - "update_attached_cluster" - ] - } - } - }, - "rest": { - "libraryClient": "AttachedClustersClient", - "rpcs": { - "CreateAttachedCluster": { - "methods": [ - "create_attached_cluster" - ] - }, - "DeleteAttachedCluster": { - "methods": [ - "delete_attached_cluster" - ] - }, - "GenerateAttachedClusterAgentToken": { - "methods": [ - "generate_attached_cluster_agent_token" - ] - }, - "GenerateAttachedClusterInstallManifest": { - "methods": [ - "generate_attached_cluster_install_manifest" - ] - }, - "GetAttachedCluster": { - "methods": [ - "get_attached_cluster" - ] - }, - "GetAttachedServerConfig": { - "methods": [ - "get_attached_server_config" - ] - }, - "ImportAttachedCluster": { - "methods": [ - "import_attached_cluster" - ] - }, - "ListAttachedClusters": { - "methods": [ - "list_attached_clusters" - ] - }, - "UpdateAttachedCluster": { - "methods": [ - "update_attached_cluster" - ] - } - } - } - } - }, - "AwsClusters": { - "clients": { - "grpc": { - "libraryClient": "AwsClustersClient", - "rpcs": { - "CreateAwsCluster": { - "methods": [ - "create_aws_cluster" - ] - }, - "CreateAwsNodePool": { - "methods": [ - "create_aws_node_pool" - ] - }, - "DeleteAwsCluster": { - "methods": [ - "delete_aws_cluster" - ] - }, - "DeleteAwsNodePool": { - "methods": [ - "delete_aws_node_pool" - ] - }, - "GenerateAwsAccessToken": { - "methods": [ - "generate_aws_access_token" - ] - }, - "GenerateAwsClusterAgentToken": { - "methods": [ - "generate_aws_cluster_agent_token" - ] - }, - "GetAwsCluster": { - "methods": [ - "get_aws_cluster" - ] - }, - "GetAwsJsonWebKeys": { - "methods": [ - "get_aws_json_web_keys" - ] - }, - "GetAwsNodePool": { - "methods": [ - "get_aws_node_pool" - ] - }, - "GetAwsOpenIdConfig": { - "methods": [ - "get_aws_open_id_config" - ] - }, - "GetAwsServerConfig": { - "methods": [ - "get_aws_server_config" - ] - }, - "ListAwsClusters": { - "methods": [ - "list_aws_clusters" - ] - }, - "ListAwsNodePools": { - "methods": [ - "list_aws_node_pools" - ] - }, - "RollbackAwsNodePoolUpdate": { - "methods": [ - "rollback_aws_node_pool_update" - ] - }, - "UpdateAwsCluster": { - "methods": [ - "update_aws_cluster" - ] - }, - "UpdateAwsNodePool": { - "methods": [ - "update_aws_node_pool" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AwsClustersAsyncClient", - "rpcs": { - "CreateAwsCluster": { - "methods": [ - "create_aws_cluster" - ] - }, - "CreateAwsNodePool": { - "methods": [ - "create_aws_node_pool" - ] - }, - "DeleteAwsCluster": { - "methods": [ - "delete_aws_cluster" - ] - }, - "DeleteAwsNodePool": { - "methods": [ - "delete_aws_node_pool" - ] - }, - "GenerateAwsAccessToken": { - "methods": [ - "generate_aws_access_token" - ] - }, - "GenerateAwsClusterAgentToken": { - "methods": [ - "generate_aws_cluster_agent_token" - ] - }, - "GetAwsCluster": { - "methods": [ - "get_aws_cluster" - ] - }, - "GetAwsJsonWebKeys": { - "methods": [ - "get_aws_json_web_keys" - ] - }, - "GetAwsNodePool": { - "methods": [ - "get_aws_node_pool" - ] - }, - "GetAwsOpenIdConfig": { - "methods": [ - "get_aws_open_id_config" - ] - }, - "GetAwsServerConfig": { - "methods": [ - "get_aws_server_config" - ] - }, - "ListAwsClusters": { - "methods": [ - "list_aws_clusters" - ] - }, - "ListAwsNodePools": { - "methods": [ - "list_aws_node_pools" - ] - }, - "RollbackAwsNodePoolUpdate": { - "methods": [ - "rollback_aws_node_pool_update" - ] - }, - "UpdateAwsCluster": { - "methods": [ - "update_aws_cluster" - ] - }, - "UpdateAwsNodePool": { - "methods": [ - "update_aws_node_pool" - ] - } - } - }, - "rest": { - "libraryClient": "AwsClustersClient", - "rpcs": { - "CreateAwsCluster": { - "methods": [ - "create_aws_cluster" - ] - }, - "CreateAwsNodePool": { - "methods": [ - "create_aws_node_pool" - ] - }, - "DeleteAwsCluster": { - "methods": [ - "delete_aws_cluster" - ] - }, - "DeleteAwsNodePool": { - "methods": [ - "delete_aws_node_pool" - ] - }, - "GenerateAwsAccessToken": { - "methods": [ - "generate_aws_access_token" - ] - }, - "GenerateAwsClusterAgentToken": { - "methods": [ - "generate_aws_cluster_agent_token" - ] - }, - "GetAwsCluster": { - "methods": [ - "get_aws_cluster" - ] - }, - "GetAwsJsonWebKeys": { - "methods": [ - "get_aws_json_web_keys" - ] - }, - "GetAwsNodePool": { - "methods": [ - "get_aws_node_pool" - ] - }, - "GetAwsOpenIdConfig": { - "methods": [ - "get_aws_open_id_config" - ] - }, - "GetAwsServerConfig": { - "methods": [ - "get_aws_server_config" - ] - }, - "ListAwsClusters": { - "methods": [ - "list_aws_clusters" - ] - }, - "ListAwsNodePools": { - "methods": [ - "list_aws_node_pools" - ] - }, - "RollbackAwsNodePoolUpdate": { - "methods": [ - "rollback_aws_node_pool_update" - ] - }, - "UpdateAwsCluster": { - "methods": [ - "update_aws_cluster" - ] - }, - "UpdateAwsNodePool": { - "methods": [ - "update_aws_node_pool" - ] - } - } - } - } - }, - "AzureClusters": { - "clients": { - "grpc": { - "libraryClient": "AzureClustersClient", - "rpcs": { - "CreateAzureClient": { - "methods": [ - "create_azure_client" - ] - }, - "CreateAzureCluster": { - "methods": [ - "create_azure_cluster" - ] - }, - "CreateAzureNodePool": { - "methods": [ - "create_azure_node_pool" - ] - }, - "DeleteAzureClient": { - "methods": [ - "delete_azure_client" - ] - }, - "DeleteAzureCluster": { - "methods": [ - "delete_azure_cluster" - ] - }, - "DeleteAzureNodePool": { - "methods": [ - "delete_azure_node_pool" - ] - }, - "GenerateAzureAccessToken": { - "methods": [ - "generate_azure_access_token" - ] - }, - "GenerateAzureClusterAgentToken": { - "methods": [ - "generate_azure_cluster_agent_token" - ] - }, - "GetAzureClient": { - "methods": [ - "get_azure_client" - ] - }, - "GetAzureCluster": { - "methods": [ - "get_azure_cluster" - ] - }, - "GetAzureJsonWebKeys": { - "methods": [ - "get_azure_json_web_keys" - ] - }, - "GetAzureNodePool": { - "methods": [ - "get_azure_node_pool" - ] - }, - "GetAzureOpenIdConfig": { - "methods": [ - "get_azure_open_id_config" - ] - }, - "GetAzureServerConfig": { - "methods": [ - "get_azure_server_config" - ] - }, - "ListAzureClients": { - "methods": [ - "list_azure_clients" - ] - }, - "ListAzureClusters": { - "methods": [ - "list_azure_clusters" - ] - }, - "ListAzureNodePools": { - "methods": [ - "list_azure_node_pools" - ] - }, - "UpdateAzureCluster": { - "methods": [ - "update_azure_cluster" - ] - }, - "UpdateAzureNodePool": { - "methods": [ - "update_azure_node_pool" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AzureClustersAsyncClient", - "rpcs": { - "CreateAzureClient": { - "methods": [ - "create_azure_client" - ] - }, - "CreateAzureCluster": { - "methods": [ - "create_azure_cluster" - ] - }, - "CreateAzureNodePool": { - "methods": [ - "create_azure_node_pool" - ] - }, - "DeleteAzureClient": { - "methods": [ - "delete_azure_client" - ] - }, - "DeleteAzureCluster": { - "methods": [ - "delete_azure_cluster" - ] - }, - "DeleteAzureNodePool": { - "methods": [ - "delete_azure_node_pool" - ] - }, - "GenerateAzureAccessToken": { - "methods": [ - "generate_azure_access_token" - ] - }, - "GenerateAzureClusterAgentToken": { - "methods": [ - "generate_azure_cluster_agent_token" - ] - }, - "GetAzureClient": { - "methods": [ - "get_azure_client" - ] - }, - "GetAzureCluster": { - "methods": [ - "get_azure_cluster" - ] - }, - "GetAzureJsonWebKeys": { - "methods": [ - "get_azure_json_web_keys" - ] - }, - "GetAzureNodePool": { - "methods": [ - "get_azure_node_pool" - ] - }, - "GetAzureOpenIdConfig": { - "methods": [ - "get_azure_open_id_config" - ] - }, - "GetAzureServerConfig": { - "methods": [ - "get_azure_server_config" - ] - }, - "ListAzureClients": { - "methods": [ - "list_azure_clients" - ] - }, - "ListAzureClusters": { - "methods": [ - "list_azure_clusters" - ] - }, - "ListAzureNodePools": { - "methods": [ - "list_azure_node_pools" - ] - }, - "UpdateAzureCluster": { - "methods": [ - "update_azure_cluster" - ] - }, - "UpdateAzureNodePool": { - "methods": [ - "update_azure_node_pool" - ] - } - } - }, - "rest": { - "libraryClient": "AzureClustersClient", - "rpcs": { - "CreateAzureClient": { - "methods": [ - "create_azure_client" - ] - }, - "CreateAzureCluster": { - "methods": [ - "create_azure_cluster" - ] - }, - "CreateAzureNodePool": { - "methods": [ - "create_azure_node_pool" - ] - }, - "DeleteAzureClient": { - "methods": [ - "delete_azure_client" - ] - }, - "DeleteAzureCluster": { - "methods": [ - "delete_azure_cluster" - ] - }, - "DeleteAzureNodePool": { - "methods": [ - "delete_azure_node_pool" - ] - }, - "GenerateAzureAccessToken": { - "methods": [ - "generate_azure_access_token" - ] - }, - "GenerateAzureClusterAgentToken": { - "methods": [ - "generate_azure_cluster_agent_token" - ] - }, - "GetAzureClient": { - "methods": [ - "get_azure_client" - ] - }, - "GetAzureCluster": { - "methods": [ - "get_azure_cluster" - ] - }, - "GetAzureJsonWebKeys": { - "methods": [ - "get_azure_json_web_keys" - ] - }, - "GetAzureNodePool": { - "methods": [ - "get_azure_node_pool" - ] - }, - "GetAzureOpenIdConfig": { - "methods": [ - "get_azure_open_id_config" - ] - }, - "GetAzureServerConfig": { - "methods": [ - "get_azure_server_config" - ] - }, - "ListAzureClients": { - "methods": [ - "list_azure_clients" - ] - }, - "ListAzureClusters": { - "methods": [ - "list_azure_clusters" - ] - }, - "ListAzureNodePools": { - "methods": [ - "list_azure_node_pools" - ] - }, - "UpdateAzureCluster": { - "methods": [ - "update_azure_cluster" - ] - }, - "UpdateAzureNodePool": { - "methods": [ - "update_azure_node_pool" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_version.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/py.typed b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/py.typed deleted file mode 100644 index 53546ad8d1e7..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-gke-multicloud package uses inline types. diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/__init__.py deleted file mode 100644 index 70436f571973..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AttachedClustersClient -from .async_client import AttachedClustersAsyncClient - -__all__ = ( - 'AttachedClustersClient', - 'AttachedClustersAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/async_client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/async_client.py deleted file mode 100644 index 79bf63e6cc67..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/async_client.py +++ /dev/null @@ -1,1691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.gke_multicloud_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.gke_multicloud_v1.services.attached_clusters import pagers -from google.cloud.gke_multicloud_v1.types import attached_resources -from google.cloud.gke_multicloud_v1.types import attached_service -from google.cloud.gke_multicloud_v1.types import common_resources -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import AttachedClustersTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AttachedClustersGrpcAsyncIOTransport -from .client import AttachedClustersClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class AttachedClustersAsyncClient: - """The AttachedClusters API provides a single centrally managed - service to register and manage Anthos attached clusters that run - on customer's owned infrastructure. - """ - - _client: AttachedClustersClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AttachedClustersClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AttachedClustersClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AttachedClustersClient._DEFAULT_UNIVERSE - - attached_cluster_path = staticmethod(AttachedClustersClient.attached_cluster_path) - parse_attached_cluster_path = staticmethod(AttachedClustersClient.parse_attached_cluster_path) - attached_server_config_path = staticmethod(AttachedClustersClient.attached_server_config_path) - parse_attached_server_config_path = staticmethod(AttachedClustersClient.parse_attached_server_config_path) - common_billing_account_path = staticmethod(AttachedClustersClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AttachedClustersClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AttachedClustersClient.common_folder_path) - parse_common_folder_path = staticmethod(AttachedClustersClient.parse_common_folder_path) - common_organization_path = staticmethod(AttachedClustersClient.common_organization_path) - parse_common_organization_path = staticmethod(AttachedClustersClient.parse_common_organization_path) - common_project_path = staticmethod(AttachedClustersClient.common_project_path) - parse_common_project_path = staticmethod(AttachedClustersClient.parse_common_project_path) - common_location_path = staticmethod(AttachedClustersClient.common_location_path) - parse_common_location_path = staticmethod(AttachedClustersClient.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: - AttachedClustersAsyncClient: The constructed client. - """ - return AttachedClustersClient.from_service_account_info.__func__(AttachedClustersAsyncClient, 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: - AttachedClustersAsyncClient: The constructed client. - """ - return AttachedClustersClient.from_service_account_file.__func__(AttachedClustersAsyncClient, 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 AttachedClustersClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AttachedClustersTransport: - """Returns the transport used by the client instance. - - Returns: - AttachedClustersTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = AttachedClustersClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AttachedClustersTransport, Callable[..., AttachedClustersTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the attached clusters async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AttachedClustersTransport,Callable[..., AttachedClustersTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the AttachedClustersTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = AttachedClustersClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.gkemulticloud_v1.AttachedClustersAsyncClient`.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "credentialsType": None, - } - ) - - async def create_attached_cluster(self, - request: Optional[Union[attached_service.CreateAttachedClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - attached_cluster: Optional[attached_resources.AttachedCluster] = None, - attached_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_create_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - attached_cluster = gke_multicloud_v1.AttachedCluster() - attached_cluster.platform_version = "platform_version_value" - attached_cluster.distribution = "distribution_value" - attached_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAttachedClusterRequest( - parent="parent_value", - attached_cluster=attached_cluster, - attached_cluster_id="attached_cluster_id_value", - ) - - # Make the request - operation = client.create_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAttachedClusterRequest, dict]]): - The request object. Request message for - ``AttachedClusters.CreateAttachedCluster`` method. - parent (:class:`str`): - Required. The parent location where this - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - attached_cluster (:class:`google.cloud.gke_multicloud_v1.types.AttachedCluster`): - Required. The specification of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - to create. - - This corresponds to the ``attached_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - attached_cluster_id (:class:`str`): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource name formatted as - ``projects//locations//attachedClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``attached_cluster_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AttachedCluster` - An Anthos cluster running on customer own - infrastructure. - - """ - # 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, attached_cluster, attached_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.CreateAttachedClusterRequest): - request = attached_service.CreateAttachedClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if attached_cluster is not None: - request.attached_cluster = attached_cluster - if attached_cluster_id is not None: - request.attached_cluster_id = attached_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_attached_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - attached_resources.AttachedCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_attached_cluster(self, - request: Optional[Union[attached_service.UpdateAttachedClusterRequest, dict]] = None, - *, - attached_cluster: Optional[attached_resources.AttachedCluster] = 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, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. - - .. 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 gke_multicloud_v1 - - async def sample_update_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - attached_cluster = gke_multicloud_v1.AttachedCluster() - attached_cluster.platform_version = "platform_version_value" - attached_cluster.distribution = "distribution_value" - attached_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAttachedClusterRequest( - attached_cluster=attached_cluster, - ) - - # Make the request - operation = client.update_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.UpdateAttachedClusterRequest, dict]]): - The request object. Request message for - ``AttachedClusters.UpdateAttachedCluster`` method. - attached_cluster (:class:`google.cloud.gke_multicloud_v1.types.AttachedCluster`): - Required. The - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource to update. - - This corresponds to the ``attached_cluster`` 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 path - must be supplied in this field. The elements of the - repeated paths field can only include these fields from - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]: - - - ``annotations``. - - ``authorization.admin_groups``. - - ``authorization.admin_users``. - - ``binary_authorization.evaluation_mode``. - - ``description``. - - ``logging_config.component_config.enable_components``. - - ``monitoring_config.managed_prometheus_config.enabled``. - - ``platform_version``. - - ``proxy_config.kubernetes_secret.name``. - - ``proxy_config.kubernetes_secret.namespace``. - - ``security_posture_config.vulnerability_mode`` - - ``monitoring_config.cloud_monitoring_config.enabled`` - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AttachedCluster` - An Anthos cluster running on customer own - infrastructure. - - """ - # 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([attached_cluster, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.UpdateAttachedClusterRequest): - request = attached_service.UpdateAttachedClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attached_cluster is not None: - request.attached_cluster = attached_cluster - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_attached_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attached_cluster.name", request.attached_cluster.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - attached_resources.AttachedCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def import_attached_cluster(self, - request: Optional[Union[attached_service.ImportAttachedClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - fleet_membership: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Imports creates a new - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource by importing an existing Fleet Membership resource. - - Attached Clusters created before the introduction of the Anthos - Multi-Cloud API can be imported through this method. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_import_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ImportAttachedClusterRequest( - parent="parent_value", - fleet_membership="fleet_membership_value", - platform_version="platform_version_value", - distribution="distribution_value", - ) - - # Make the request - operation = client.import_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.ImportAttachedClusterRequest, dict]]): - The request object. Request message for - ``AttachedClusters.ImportAttachedCluster`` method. - parent (:class:`str`): - Required. The parent location where this - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - fleet_membership (:class:`str`): - Required. The name of the fleet - membership resource to import. - - This corresponds to the ``fleet_membership`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AttachedCluster` - An Anthos cluster running on customer own - infrastructure. - - """ - # 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, fleet_membership]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.ImportAttachedClusterRequest): - request = attached_service.ImportAttachedClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if fleet_membership is not None: - request.fleet_membership = fleet_membership - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.import_attached_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - attached_resources.AttachedCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_attached_cluster(self, - request: Optional[Union[attached_service.GetAttachedClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> attached_resources.AttachedCluster: - r"""Describes a specific - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - 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 gke_multicloud_v1 - - async def sample_get_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAttachedClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attached_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAttachedClusterRequest, dict]]): - The request object. Request message for - ``AttachedClusters.GetAttachedCluster`` method. - name (:class:`str`): - Required. The name of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource to describe. - - ``AttachedCluster`` names are formatted as - ``projects//locations//attachedClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AttachedCluster: - An Anthos cluster running on customer - own infrastructure. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.GetAttachedClusterRequest): - request = attached_service.GetAttachedClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_attached_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_attached_clusters(self, - request: Optional[Union[attached_service.ListAttachedClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAttachedClustersAsyncPager: - r"""Lists all - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resources on a given Google Cloud project and region. - - .. 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 gke_multicloud_v1 - - async def sample_list_attached_clusters(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAttachedClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attached_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest, dict]]): - The request object. Request message for - ``AttachedClusters.ListAttachedClusters`` method. - parent (:class:`str`): - Required. The parent location which owns this collection - of - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.attached_clusters.pagers.ListAttachedClustersAsyncPager: - Response message for - AttachedClusters.ListAttachedClusters method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.ListAttachedClustersRequest): - request = attached_service.ListAttachedClustersRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_attached_clusters] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAttachedClustersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_attached_cluster(self, - request: Optional[Union[attached_service.DeleteAttachedClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a specific - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_delete_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAttachedClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAttachedClusterRequest, dict]]): - The request object. Request message for - ``AttachedClusters.DeleteAttachedCluster`` method. - name (:class:`str`): - Required. The resource name the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - to delete. - - ``AttachedCluster`` names are formatted as - ``projects//locations//attachedClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.DeleteAttachedClusterRequest): - request = attached_service.DeleteAttachedClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_attached_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_attached_server_config(self, - request: Optional[Union[attached_service.GetAttachedServerConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> attached_resources.AttachedServerConfig: - r"""Returns information, such as supported Kubernetes - versions, on a given Google Cloud 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 gke_multicloud_v1 - - async def sample_get_attached_server_config(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAttachedServerConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attached_server_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAttachedServerConfigRequest, dict]]): - The request object. GetAttachedServerConfigRequest gets - the server config for attached clusters. - name (:class:`str`): - Required. The name of the - [AttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedServerConfig] - resource to describe. - - ``AttachedServerConfig`` names are formatted as - ``projects//locations//attachedServerConfig``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AttachedServerConfig: - AttachedServerConfig provides - information about supported Kubernetes - versions - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.GetAttachedServerConfigRequest): - request = attached_service.GetAttachedServerConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_attached_server_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def generate_attached_cluster_install_manifest(self, - request: Optional[Union[attached_service.GenerateAttachedClusterInstallManifestRequest, dict]] = None, - *, - parent: Optional[str] = None, - attached_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> attached_service.GenerateAttachedClusterInstallManifestResponse: - r"""Generates the install manifest to be installed on the - target 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 gke_multicloud_v1 - - async def sample_generate_attached_cluster_install_manifest(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAttachedClusterInstallManifestRequest( - parent="parent_value", - attached_cluster_id="attached_cluster_id_value", - platform_version="platform_version_value", - ) - - # Make the request - response = await client.generate_attached_cluster_install_manifest(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestRequest, dict]]): - The request object. Request message for - ``AttachedClusters.GenerateAttachedClusterInstallManifest`` - method. - parent (:class:`str`): - Required. The parent location where this - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - attached_cluster_id (:class:`str`): - Required. A client provided ID of the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource name formatted as - ``projects//locations//attachedClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - When generating an install manifest for importing an - existing Membership resource, the attached_cluster_id - field must be the Membership id. - - Membership names are formatted as - ``projects//locations//memberships/``. - - This corresponds to the ``attached_cluster_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestResponse: - Response message for - AttachedClusters.GenerateAttachedClusterInstallManifest - method. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, attached_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.GenerateAttachedClusterInstallManifestRequest): - request = attached_service.GenerateAttachedClusterInstallManifestRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if attached_cluster_id is not None: - request.attached_cluster_id = attached_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_attached_cluster_install_manifest] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def generate_attached_cluster_agent_token(self, - request: Optional[Union[attached_service.GenerateAttachedClusterAgentTokenRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> attached_service.GenerateAttachedClusterAgentTokenResponse: - r"""Generates an access token for a cluster agent. - - .. 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 gke_multicloud_v1 - - async def sample_generate_attached_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAttachedClusterAgentTokenRequest( - attached_cluster="attached_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = await client.generate_attached_cluster_agent_token(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenRequest, dict]]): - The request object. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenResponse: - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.GenerateAttachedClusterAgentTokenRequest): - request = attached_service.GenerateAttachedClusterAgentTokenRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_attached_cluster_agent_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attached_cluster", request.attached_cluster), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.list_operations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def 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, Union[str, bytes]]] = (), - ) -> 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_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.delete_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - 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, Union[str, bytes]]] = (), - ) -> 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_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.cancel_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self) -> "AttachedClustersAsyncClient": - 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__ = ( - "AttachedClustersAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/client.py deleted file mode 100644 index 90e2468d03a0..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/client.py +++ /dev/null @@ -1,2028 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.gke_multicloud_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.gke_multicloud_v1.services.attached_clusters import pagers -from google.cloud.gke_multicloud_v1.types import attached_resources -from google.cloud.gke_multicloud_v1.types import attached_service -from google.cloud.gke_multicloud_v1.types import common_resources -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import AttachedClustersTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AttachedClustersGrpcTransport -from .transports.grpc_asyncio import AttachedClustersGrpcAsyncIOTransport -from .transports.rest import AttachedClustersRestTransport - - -class AttachedClustersClientMeta(type): - """Metaclass for the AttachedClusters 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[AttachedClustersTransport]] - _transport_registry["grpc"] = AttachedClustersGrpcTransport - _transport_registry["grpc_asyncio"] = AttachedClustersGrpcAsyncIOTransport - _transport_registry["rest"] = AttachedClustersRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AttachedClustersTransport]: - """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 AttachedClustersClient(metaclass=AttachedClustersClientMeta): - """The AttachedClusters API provides a single centrally managed - service to register and manage Anthos attached clusters that run - on customer's owned infrastructure. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "gkemulticloud.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "gkemulticloud.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AttachedClustersClient: 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: - AttachedClustersClient: 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) -> AttachedClustersTransport: - """Returns the transport used by the client instance. - - Returns: - AttachedClustersTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def attached_cluster_path(project: str,location: str,attached_cluster: str,) -> str: - """Returns a fully-qualified attached_cluster string.""" - return "projects/{project}/locations/{location}/attachedClusters/{attached_cluster}".format(project=project, location=location, attached_cluster=attached_cluster, ) - - @staticmethod - def parse_attached_cluster_path(path: str) -> Dict[str,str]: - """Parses a attached_cluster path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/attachedClusters/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def attached_server_config_path(project: str,location: str,) -> str: - """Returns a fully-qualified attached_server_config string.""" - return "projects/{project}/locations/{location}/attachedServerConfig".format(project=project, location=location, ) - - @staticmethod - def parse_attached_server_config_path(path: str) -> Dict[str,str]: - """Parses a attached_server_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/attachedServerConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = AttachedClustersClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AttachedClustersClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = AttachedClustersClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AttachedClustersTransport, Callable[..., AttachedClustersTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the attached clusters client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AttachedClustersTransport,Callable[..., AttachedClustersTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the AttachedClustersTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AttachedClustersClient._read_environment_variables() - self._client_cert_source = AttachedClustersClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AttachedClustersClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, AttachedClustersTransport) - if transport_provided: - # transport is a AttachedClustersTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(AttachedClustersTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AttachedClustersClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[AttachedClustersTransport], Callable[..., AttachedClustersTransport]] = ( - AttachedClustersClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AttachedClustersTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.gkemulticloud_v1.AttachedClustersClient`.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "credentialsType": None, - } - ) - - def create_attached_cluster(self, - request: Optional[Union[attached_service.CreateAttachedClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - attached_cluster: Optional[attached_resources.AttachedCluster] = None, - attached_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_create_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - attached_cluster = gke_multicloud_v1.AttachedCluster() - attached_cluster.platform_version = "platform_version_value" - attached_cluster.distribution = "distribution_value" - attached_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAttachedClusterRequest( - parent="parent_value", - attached_cluster=attached_cluster, - attached_cluster_id="attached_cluster_id_value", - ) - - # Make the request - operation = client.create_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.CreateAttachedClusterRequest, dict]): - The request object. Request message for - ``AttachedClusters.CreateAttachedCluster`` method. - parent (str): - Required. The parent location where this - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - attached_cluster (google.cloud.gke_multicloud_v1.types.AttachedCluster): - Required. The specification of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - to create. - - This corresponds to the ``attached_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - attached_cluster_id (str): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource name formatted as - ``projects//locations//attachedClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``attached_cluster_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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AttachedCluster` - An Anthos cluster running on customer own - infrastructure. - - """ - # 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, attached_cluster, attached_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.CreateAttachedClusterRequest): - request = attached_service.CreateAttachedClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if attached_cluster is not None: - request.attached_cluster = attached_cluster - if attached_cluster_id is not None: - request.attached_cluster_id = attached_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_attached_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - attached_resources.AttachedCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_attached_cluster(self, - request: Optional[Union[attached_service.UpdateAttachedClusterRequest, dict]] = None, - *, - attached_cluster: Optional[attached_resources.AttachedCluster] = 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, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates an - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. - - .. 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 gke_multicloud_v1 - - def sample_update_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - attached_cluster = gke_multicloud_v1.AttachedCluster() - attached_cluster.platform_version = "platform_version_value" - attached_cluster.distribution = "distribution_value" - attached_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAttachedClusterRequest( - attached_cluster=attached_cluster, - ) - - # Make the request - operation = client.update_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.UpdateAttachedClusterRequest, dict]): - The request object. Request message for - ``AttachedClusters.UpdateAttachedCluster`` method. - attached_cluster (google.cloud.gke_multicloud_v1.types.AttachedCluster): - Required. The - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource to update. - - This corresponds to the ``attached_cluster`` 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 path - must be supplied in this field. The elements of the - repeated paths field can only include these fields from - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]: - - - ``annotations``. - - ``authorization.admin_groups``. - - ``authorization.admin_users``. - - ``binary_authorization.evaluation_mode``. - - ``description``. - - ``logging_config.component_config.enable_components``. - - ``monitoring_config.managed_prometheus_config.enabled``. - - ``platform_version``. - - ``proxy_config.kubernetes_secret.name``. - - ``proxy_config.kubernetes_secret.namespace``. - - ``security_posture_config.vulnerability_mode`` - - ``monitoring_config.cloud_monitoring_config.enabled`` - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AttachedCluster` - An Anthos cluster running on customer own - infrastructure. - - """ - # 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([attached_cluster, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.UpdateAttachedClusterRequest): - request = attached_service.UpdateAttachedClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if attached_cluster is not None: - request.attached_cluster = attached_cluster - 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_attached_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attached_cluster.name", request.attached_cluster.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - attached_resources.AttachedCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def import_attached_cluster(self, - request: Optional[Union[attached_service.ImportAttachedClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - fleet_membership: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Imports creates a new - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource by importing an existing Fleet Membership resource. - - Attached Clusters created before the introduction of the Anthos - Multi-Cloud API can be imported through this method. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_import_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ImportAttachedClusterRequest( - parent="parent_value", - fleet_membership="fleet_membership_value", - platform_version="platform_version_value", - distribution="distribution_value", - ) - - # Make the request - operation = client.import_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.ImportAttachedClusterRequest, dict]): - The request object. Request message for - ``AttachedClusters.ImportAttachedCluster`` method. - parent (str): - Required. The parent location where this - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - fleet_membership (str): - Required. The name of the fleet - membership resource to import. - - This corresponds to the ``fleet_membership`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AttachedCluster` - An Anthos cluster running on customer own - infrastructure. - - """ - # 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, fleet_membership]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.ImportAttachedClusterRequest): - request = attached_service.ImportAttachedClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if fleet_membership is not None: - request.fleet_membership = fleet_membership - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_attached_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - attached_resources.AttachedCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_attached_cluster(self, - request: Optional[Union[attached_service.GetAttachedClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> attached_resources.AttachedCluster: - r"""Describes a specific - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - 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 gke_multicloud_v1 - - def sample_get_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAttachedClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_attached_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAttachedClusterRequest, dict]): - The request object. Request message for - ``AttachedClusters.GetAttachedCluster`` method. - name (str): - Required. The name of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource to describe. - - ``AttachedCluster`` names are formatted as - ``projects//locations//attachedClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AttachedCluster: - An Anthos cluster running on customer - own infrastructure. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.GetAttachedClusterRequest): - request = attached_service.GetAttachedClusterRequest(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_attached_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_attached_clusters(self, - request: Optional[Union[attached_service.ListAttachedClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAttachedClustersPager: - r"""Lists all - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resources on a given Google Cloud project and region. - - .. 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 gke_multicloud_v1 - - def sample_list_attached_clusters(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAttachedClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attached_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest, dict]): - The request object. Request message for - ``AttachedClusters.ListAttachedClusters`` method. - parent (str): - Required. The parent location which owns this collection - of - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.attached_clusters.pagers.ListAttachedClustersPager: - Response message for - AttachedClusters.ListAttachedClusters method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.ListAttachedClustersRequest): - request = attached_service.ListAttachedClustersRequest(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_attached_clusters] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAttachedClustersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_attached_cluster(self, - request: Optional[Union[attached_service.DeleteAttachedClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a specific - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_delete_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAttachedClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.DeleteAttachedClusterRequest, dict]): - The request object. Request message for - ``AttachedClusters.DeleteAttachedCluster`` method. - name (str): - Required. The resource name the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - to delete. - - ``AttachedCluster`` names are formatted as - ``projects//locations//attachedClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.DeleteAttachedClusterRequest): - request = attached_service.DeleteAttachedClusterRequest(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_attached_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_attached_server_config(self, - request: Optional[Union[attached_service.GetAttachedServerConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> attached_resources.AttachedServerConfig: - r"""Returns information, such as supported Kubernetes - versions, on a given Google Cloud 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 gke_multicloud_v1 - - def sample_get_attached_server_config(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAttachedServerConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attached_server_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAttachedServerConfigRequest, dict]): - The request object. GetAttachedServerConfigRequest gets - the server config for attached clusters. - name (str): - Required. The name of the - [AttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedServerConfig] - resource to describe. - - ``AttachedServerConfig`` names are formatted as - ``projects//locations//attachedServerConfig``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AttachedServerConfig: - AttachedServerConfig provides - information about supported Kubernetes - versions - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.GetAttachedServerConfigRequest): - request = attached_service.GetAttachedServerConfigRequest(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_attached_server_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_attached_cluster_install_manifest(self, - request: Optional[Union[attached_service.GenerateAttachedClusterInstallManifestRequest, dict]] = None, - *, - parent: Optional[str] = None, - attached_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> attached_service.GenerateAttachedClusterInstallManifestResponse: - r"""Generates the install manifest to be installed on the - target 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 gke_multicloud_v1 - - def sample_generate_attached_cluster_install_manifest(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAttachedClusterInstallManifestRequest( - parent="parent_value", - attached_cluster_id="attached_cluster_id_value", - platform_version="platform_version_value", - ) - - # Make the request - response = client.generate_attached_cluster_install_manifest(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestRequest, dict]): - The request object. Request message for - ``AttachedClusters.GenerateAttachedClusterInstallManifest`` - method. - parent (str): - Required. The parent location where this - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - attached_cluster_id (str): - Required. A client provided ID of the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource name formatted as - ``projects//locations//attachedClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - When generating an install manifest for importing an - existing Membership resource, the attached_cluster_id - field must be the Membership id. - - Membership names are formatted as - ``projects//locations//memberships/``. - - This corresponds to the ``attached_cluster_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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestResponse: - Response message for - AttachedClusters.GenerateAttachedClusterInstallManifest - method. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, attached_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.GenerateAttachedClusterInstallManifestRequest): - request = attached_service.GenerateAttachedClusterInstallManifestRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if attached_cluster_id is not None: - request.attached_cluster_id = attached_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_attached_cluster_install_manifest] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_attached_cluster_agent_token(self, - request: Optional[Union[attached_service.GenerateAttachedClusterAgentTokenRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> attached_service.GenerateAttachedClusterAgentTokenResponse: - r"""Generates an access token for a cluster agent. - - .. 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 gke_multicloud_v1 - - def sample_generate_attached_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAttachedClusterAgentTokenRequest( - attached_cluster="attached_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = client.generate_attached_cluster_agent_token(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenRequest, dict]): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenResponse: - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, attached_service.GenerateAttachedClusterAgentTokenRequest): - request = attached_service.GenerateAttachedClusterAgentTokenRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_attached_cluster_agent_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("attached_cluster", request.attached_cluster), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AttachedClustersClient": - 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, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.list_operations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def 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, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.delete_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - 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, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.cancel_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AttachedClustersClient", -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/pagers.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/pagers.py deleted file mode 100644 index 7c9b1f9cba56..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/pagers.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.cloud.gke_multicloud_v1.types import attached_resources -from google.cloud.gke_multicloud_v1.types import attached_service - - -class ListAttachedClustersPager: - """A pager for iterating through ``list_attached_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``attached_clusters`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAttachedClusters`` requests and continue to iterate - through the ``attached_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse` - 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[..., attached_service.ListAttachedClustersResponse], - request: attached_service.ListAttachedClustersRequest, - response: attached_service.ListAttachedClustersResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = attached_service.ListAttachedClustersRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[attached_service.ListAttachedClustersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[attached_resources.AttachedCluster]: - for page in self.pages: - yield from page.attached_clusters - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAttachedClustersAsyncPager: - """A pager for iterating through ``list_attached_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``attached_clusters`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAttachedClusters`` requests and continue to iterate - through the ``attached_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse` - 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[attached_service.ListAttachedClustersResponse]], - request: attached_service.ListAttachedClustersRequest, - response: attached_service.ListAttachedClustersResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAttachedClustersResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = attached_service.ListAttachedClustersRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[attached_service.ListAttachedClustersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[attached_resources.AttachedCluster]: - async def async_generator(): - async for page in self.pages: - for response in page.attached_clusters: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/README.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/README.rst deleted file mode 100644 index 6dc5686bab67..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AttachedClustersTransport` is the ABC for all transports. -- public child `AttachedClustersGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AttachedClustersGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAttachedClustersRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AttachedClustersRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/__init__.py deleted file mode 100644 index 73db2bf098c5..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AttachedClustersTransport -from .grpc import AttachedClustersGrpcTransport -from .grpc_asyncio import AttachedClustersGrpcAsyncIOTransport -from .rest import AttachedClustersRestTransport -from .rest import AttachedClustersRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AttachedClustersTransport]] -_transport_registry['grpc'] = AttachedClustersGrpcTransport -_transport_registry['grpc_asyncio'] = AttachedClustersGrpcAsyncIOTransport -_transport_registry['rest'] = AttachedClustersRestTransport - -__all__ = ( - 'AttachedClustersTransport', - 'AttachedClustersGrpcTransport', - 'AttachedClustersGrpcAsyncIOTransport', - 'AttachedClustersRestTransport', - 'AttachedClustersRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/base.py deleted file mode 100644 index 55700e7ce90a..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/base.py +++ /dev/null @@ -1,375 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.gke_multicloud_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.gke_multicloud_v1.types import attached_resources -from google.cloud.gke_multicloud_v1.types import attached_service -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AttachedClustersTransport(abc.ABC): - """Abstract transport class for AttachedClusters.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'gkemulticloud.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_attached_cluster: gapic_v1.method.wrap_method( - self.create_attached_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_attached_cluster: gapic_v1.method.wrap_method( - self.update_attached_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.import_attached_cluster: gapic_v1.method.wrap_method( - self.import_attached_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_attached_cluster: gapic_v1.method.wrap_method( - self.get_attached_cluster, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_attached_clusters: gapic_v1.method.wrap_method( - self.list_attached_clusters, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_attached_cluster: gapic_v1.method.wrap_method( - self.delete_attached_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_attached_server_config: gapic_v1.method.wrap_method( - self.get_attached_server_config, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_attached_cluster_install_manifest: gapic_v1.method.wrap_method( - self.generate_attached_cluster_install_manifest, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_attached_cluster_agent_token: gapic_v1.method.wrap_method( - self.generate_attached_cluster_agent_token, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - 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 create_attached_cluster(self) -> Callable[ - [attached_service.CreateAttachedClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_attached_cluster(self) -> Callable[ - [attached_service.UpdateAttachedClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_attached_cluster(self) -> Callable[ - [attached_service.ImportAttachedClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_attached_cluster(self) -> Callable[ - [attached_service.GetAttachedClusterRequest], - Union[ - attached_resources.AttachedCluster, - Awaitable[attached_resources.AttachedCluster] - ]]: - raise NotImplementedError() - - @property - def list_attached_clusters(self) -> Callable[ - [attached_service.ListAttachedClustersRequest], - Union[ - attached_service.ListAttachedClustersResponse, - Awaitable[attached_service.ListAttachedClustersResponse] - ]]: - raise NotImplementedError() - - @property - def delete_attached_cluster(self) -> Callable[ - [attached_service.DeleteAttachedClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_attached_server_config(self) -> Callable[ - [attached_service.GetAttachedServerConfigRequest], - Union[ - attached_resources.AttachedServerConfig, - Awaitable[attached_resources.AttachedServerConfig] - ]]: - raise NotImplementedError() - - @property - def generate_attached_cluster_install_manifest(self) -> Callable[ - [attached_service.GenerateAttachedClusterInstallManifestRequest], - Union[ - attached_service.GenerateAttachedClusterInstallManifestResponse, - Awaitable[attached_service.GenerateAttachedClusterInstallManifestResponse] - ]]: - raise NotImplementedError() - - @property - def generate_attached_cluster_agent_token(self) -> Callable[ - [attached_service.GenerateAttachedClusterAgentTokenRequest], - Union[ - attached_service.GenerateAttachedClusterAgentTokenResponse, - Awaitable[attached_service.GenerateAttachedClusterAgentTokenResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AttachedClustersTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc.py deleted file mode 100644 index ee820d99e000..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc.py +++ /dev/null @@ -1,679 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -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 -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.cloud.gke_multicloud_v1.types import attached_resources -from google.cloud.gke_multicloud_v1.types import attached_service -from google.longrunning import operations_pb2 # type: ignore -from .base import AttachedClustersTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": client_call_details.method, - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AttachedClustersGrpcTransport(AttachedClustersTransport): - """gRPC backend transport for AttachedClusters. - - The AttachedClusters API provides a single centrally managed - service to register and manage Anthos attached clusters that run - on customer's owned infrastructure. - - 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 = 'gkemulticloud.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'gkemulticloud.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._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_attached_cluster(self) -> Callable[ - [attached_service.CreateAttachedClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the create attached cluster method over gRPC. - - Creates a new - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAttachedClusterRequest], - ~.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_attached_cluster' not in self._stubs: - self._stubs['create_attached_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/CreateAttachedCluster', - request_serializer=attached_service.CreateAttachedClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_attached_cluster'] - - @property - def update_attached_cluster(self) -> Callable[ - [attached_service.UpdateAttachedClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the update attached cluster method over gRPC. - - Updates an - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. - - Returns: - Callable[[~.UpdateAttachedClusterRequest], - ~.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_attached_cluster' not in self._stubs: - self._stubs['update_attached_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/UpdateAttachedCluster', - request_serializer=attached_service.UpdateAttachedClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_attached_cluster'] - - @property - def import_attached_cluster(self) -> Callable[ - [attached_service.ImportAttachedClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the import attached cluster method over gRPC. - - Imports creates a new - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource by importing an existing Fleet Membership resource. - - Attached Clusters created before the introduction of the Anthos - Multi-Cloud API can be imported through this method. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.ImportAttachedClusterRequest], - ~.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 'import_attached_cluster' not in self._stubs: - self._stubs['import_attached_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/ImportAttachedCluster', - request_serializer=attached_service.ImportAttachedClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_attached_cluster'] - - @property - def get_attached_cluster(self) -> Callable[ - [attached_service.GetAttachedClusterRequest], - attached_resources.AttachedCluster]: - r"""Return a callable for the get attached cluster method over gRPC. - - Describes a specific - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource. - - Returns: - Callable[[~.GetAttachedClusterRequest], - ~.AttachedCluster]: - 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_attached_cluster' not in self._stubs: - self._stubs['get_attached_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/GetAttachedCluster', - request_serializer=attached_service.GetAttachedClusterRequest.serialize, - response_deserializer=attached_resources.AttachedCluster.deserialize, - ) - return self._stubs['get_attached_cluster'] - - @property - def list_attached_clusters(self) -> Callable[ - [attached_service.ListAttachedClustersRequest], - attached_service.ListAttachedClustersResponse]: - r"""Return a callable for the list attached clusters method over gRPC. - - Lists all - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resources on a given Google Cloud project and region. - - Returns: - Callable[[~.ListAttachedClustersRequest], - ~.ListAttachedClustersResponse]: - 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_attached_clusters' not in self._stubs: - self._stubs['list_attached_clusters'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/ListAttachedClusters', - request_serializer=attached_service.ListAttachedClustersRequest.serialize, - response_deserializer=attached_service.ListAttachedClustersResponse.deserialize, - ) - return self._stubs['list_attached_clusters'] - - @property - def delete_attached_cluster(self) -> Callable[ - [attached_service.DeleteAttachedClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete attached cluster method over gRPC. - - Deletes a specific - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAttachedClusterRequest], - ~.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_attached_cluster' not in self._stubs: - self._stubs['delete_attached_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/DeleteAttachedCluster', - request_serializer=attached_service.DeleteAttachedClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_attached_cluster'] - - @property - def get_attached_server_config(self) -> Callable[ - [attached_service.GetAttachedServerConfigRequest], - attached_resources.AttachedServerConfig]: - r"""Return a callable for the get attached server config method over gRPC. - - Returns information, such as supported Kubernetes - versions, on a given Google Cloud location. - - Returns: - Callable[[~.GetAttachedServerConfigRequest], - ~.AttachedServerConfig]: - 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_attached_server_config' not in self._stubs: - self._stubs['get_attached_server_config'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/GetAttachedServerConfig', - request_serializer=attached_service.GetAttachedServerConfigRequest.serialize, - response_deserializer=attached_resources.AttachedServerConfig.deserialize, - ) - return self._stubs['get_attached_server_config'] - - @property - def generate_attached_cluster_install_manifest(self) -> Callable[ - [attached_service.GenerateAttachedClusterInstallManifestRequest], - attached_service.GenerateAttachedClusterInstallManifestResponse]: - r"""Return a callable for the generate attached cluster - install manifest method over gRPC. - - Generates the install manifest to be installed on the - target cluster. - - Returns: - Callable[[~.GenerateAttachedClusterInstallManifestRequest], - ~.GenerateAttachedClusterInstallManifestResponse]: - 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_attached_cluster_install_manifest' not in self._stubs: - self._stubs['generate_attached_cluster_install_manifest'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/GenerateAttachedClusterInstallManifest', - request_serializer=attached_service.GenerateAttachedClusterInstallManifestRequest.serialize, - response_deserializer=attached_service.GenerateAttachedClusterInstallManifestResponse.deserialize, - ) - return self._stubs['generate_attached_cluster_install_manifest'] - - @property - def generate_attached_cluster_agent_token(self) -> Callable[ - [attached_service.GenerateAttachedClusterAgentTokenRequest], - attached_service.GenerateAttachedClusterAgentTokenResponse]: - r"""Return a callable for the generate attached cluster - agent token method over gRPC. - - Generates an access token for a cluster agent. - - Returns: - Callable[[~.GenerateAttachedClusterAgentTokenRequest], - ~.GenerateAttachedClusterAgentTokenResponse]: - 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_attached_cluster_agent_token' not in self._stubs: - self._stubs['generate_attached_cluster_agent_token'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/GenerateAttachedClusterAgentToken', - request_serializer=attached_service.GenerateAttachedClusterAgentTokenRequest.serialize, - response_deserializer=attached_service.GenerateAttachedClusterAgentTokenResponse.deserialize, - ) - return self._stubs['generate_attached_cluster_agent_token'] - - def close(self): - self._logged_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._logged_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._logged_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._logged_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._logged_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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AttachedClustersGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc_asyncio.py deleted file mode 100644 index 937686a8132b..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/grpc_asyncio.py +++ /dev/null @@ -1,804 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -import logging as std_logging -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.gke_multicloud_v1.types import attached_resources -from google.cloud.gke_multicloud_v1.types import attached_service -from google.longrunning import operations_pb2 # type: ignore -from .base import AttachedClustersTransport, DEFAULT_CLIENT_INFO -from .grpc import AttachedClustersGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AttachedClustersGrpcAsyncIOTransport(AttachedClustersTransport): - """gRPC AsyncIO backend transport for AttachedClusters. - - The AttachedClusters API provides a single centrally managed - service to register and manage Anthos attached clusters that run - on customer's owned infrastructure. - - 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 = 'gkemulticloud.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'gkemulticloud.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_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._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_attached_cluster(self) -> Callable[ - [attached_service.CreateAttachedClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create attached cluster method over gRPC. - - Creates a new - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAttachedClusterRequest], - 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_attached_cluster' not in self._stubs: - self._stubs['create_attached_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/CreateAttachedCluster', - request_serializer=attached_service.CreateAttachedClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_attached_cluster'] - - @property - def update_attached_cluster(self) -> Callable[ - [attached_service.UpdateAttachedClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update attached cluster method over gRPC. - - Updates an - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. - - Returns: - Callable[[~.UpdateAttachedClusterRequest], - 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_attached_cluster' not in self._stubs: - self._stubs['update_attached_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/UpdateAttachedCluster', - request_serializer=attached_service.UpdateAttachedClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_attached_cluster'] - - @property - def import_attached_cluster(self) -> Callable[ - [attached_service.ImportAttachedClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import attached cluster method over gRPC. - - Imports creates a new - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource by importing an existing Fleet Membership resource. - - Attached Clusters created before the introduction of the Anthos - Multi-Cloud API can be imported through this method. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.ImportAttachedClusterRequest], - 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 'import_attached_cluster' not in self._stubs: - self._stubs['import_attached_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/ImportAttachedCluster', - request_serializer=attached_service.ImportAttachedClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_attached_cluster'] - - @property - def get_attached_cluster(self) -> Callable[ - [attached_service.GetAttachedClusterRequest], - Awaitable[attached_resources.AttachedCluster]]: - r"""Return a callable for the get attached cluster method over gRPC. - - Describes a specific - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource. - - Returns: - Callable[[~.GetAttachedClusterRequest], - Awaitable[~.AttachedCluster]]: - 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_attached_cluster' not in self._stubs: - self._stubs['get_attached_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/GetAttachedCluster', - request_serializer=attached_service.GetAttachedClusterRequest.serialize, - response_deserializer=attached_resources.AttachedCluster.deserialize, - ) - return self._stubs['get_attached_cluster'] - - @property - def list_attached_clusters(self) -> Callable[ - [attached_service.ListAttachedClustersRequest], - Awaitable[attached_service.ListAttachedClustersResponse]]: - r"""Return a callable for the list attached clusters method over gRPC. - - Lists all - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resources on a given Google Cloud project and region. - - Returns: - Callable[[~.ListAttachedClustersRequest], - Awaitable[~.ListAttachedClustersResponse]]: - 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_attached_clusters' not in self._stubs: - self._stubs['list_attached_clusters'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/ListAttachedClusters', - request_serializer=attached_service.ListAttachedClustersRequest.serialize, - response_deserializer=attached_service.ListAttachedClustersResponse.deserialize, - ) - return self._stubs['list_attached_clusters'] - - @property - def delete_attached_cluster(self) -> Callable[ - [attached_service.DeleteAttachedClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete attached cluster method over gRPC. - - Deletes a specific - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAttachedClusterRequest], - 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_attached_cluster' not in self._stubs: - self._stubs['delete_attached_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/DeleteAttachedCluster', - request_serializer=attached_service.DeleteAttachedClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_attached_cluster'] - - @property - def get_attached_server_config(self) -> Callable[ - [attached_service.GetAttachedServerConfigRequest], - Awaitable[attached_resources.AttachedServerConfig]]: - r"""Return a callable for the get attached server config method over gRPC. - - Returns information, such as supported Kubernetes - versions, on a given Google Cloud location. - - Returns: - Callable[[~.GetAttachedServerConfigRequest], - Awaitable[~.AttachedServerConfig]]: - 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_attached_server_config' not in self._stubs: - self._stubs['get_attached_server_config'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/GetAttachedServerConfig', - request_serializer=attached_service.GetAttachedServerConfigRequest.serialize, - response_deserializer=attached_resources.AttachedServerConfig.deserialize, - ) - return self._stubs['get_attached_server_config'] - - @property - def generate_attached_cluster_install_manifest(self) -> Callable[ - [attached_service.GenerateAttachedClusterInstallManifestRequest], - Awaitable[attached_service.GenerateAttachedClusterInstallManifestResponse]]: - r"""Return a callable for the generate attached cluster - install manifest method over gRPC. - - Generates the install manifest to be installed on the - target cluster. - - Returns: - Callable[[~.GenerateAttachedClusterInstallManifestRequest], - Awaitable[~.GenerateAttachedClusterInstallManifestResponse]]: - 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_attached_cluster_install_manifest' not in self._stubs: - self._stubs['generate_attached_cluster_install_manifest'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/GenerateAttachedClusterInstallManifest', - request_serializer=attached_service.GenerateAttachedClusterInstallManifestRequest.serialize, - response_deserializer=attached_service.GenerateAttachedClusterInstallManifestResponse.deserialize, - ) - return self._stubs['generate_attached_cluster_install_manifest'] - - @property - def generate_attached_cluster_agent_token(self) -> Callable[ - [attached_service.GenerateAttachedClusterAgentTokenRequest], - Awaitable[attached_service.GenerateAttachedClusterAgentTokenResponse]]: - r"""Return a callable for the generate attached cluster - agent token method over gRPC. - - Generates an access token for a cluster agent. - - Returns: - Callable[[~.GenerateAttachedClusterAgentTokenRequest], - Awaitable[~.GenerateAttachedClusterAgentTokenResponse]]: - 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_attached_cluster_agent_token' not in self._stubs: - self._stubs['generate_attached_cluster_agent_token'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AttachedClusters/GenerateAttachedClusterAgentToken', - request_serializer=attached_service.GenerateAttachedClusterAgentTokenRequest.serialize, - response_deserializer=attached_service.GenerateAttachedClusterAgentTokenResponse.deserialize, - ) - return self._stubs['generate_attached_cluster_agent_token'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.create_attached_cluster: self._wrap_method( - self.create_attached_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_attached_cluster: self._wrap_method( - self.update_attached_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.import_attached_cluster: self._wrap_method( - self.import_attached_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_attached_cluster: self._wrap_method( - self.get_attached_cluster, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_attached_clusters: self._wrap_method( - self.list_attached_clusters, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_attached_cluster: self._wrap_method( - self.delete_attached_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_attached_server_config: self._wrap_method( - self.get_attached_server_config, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_attached_cluster_install_manifest: self._wrap_method( - self.generate_attached_cluster_install_manifest, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_attached_cluster_agent_token: self._wrap_method( - self.generate_attached_cluster_agent_token, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @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._logged_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._logged_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._logged_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._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'AttachedClustersGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest.py deleted file mode 100644 index 521ec7afd435..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest.py +++ /dev/null @@ -1,2131 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # 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 gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.gke_multicloud_v1.types import attached_resources -from google.cloud.gke_multicloud_v1.types import attached_service -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseAttachedClustersRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class AttachedClustersRestInterceptor: - """Interceptor for AttachedClusters. - - 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 AttachedClustersRestTransport. - - .. code-block:: python - class MyCustomAttachedClustersInterceptor(AttachedClustersRestInterceptor): - def pre_create_attached_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_attached_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_attached_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_attached_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_attached_cluster_agent_token(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_attached_cluster_agent_token(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_attached_cluster_install_manifest(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_attached_cluster_install_manifest(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_attached_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_attached_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_attached_server_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_attached_server_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_attached_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_attached_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_attached_clusters(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_attached_clusters(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_attached_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_attached_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AttachedClustersRestTransport(interceptor=MyCustomAttachedClustersInterceptor()) - client = AttachedClustersClient(transport=transport) - - - """ - def pre_create_attached_cluster(self, request: attached_service.CreateAttachedClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.CreateAttachedClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_attached_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters server. - """ - return request, metadata - - def post_create_attached_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_attached_cluster - - Override in a subclass to manipulate the response - after it is returned by the AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_delete_attached_cluster(self, request: attached_service.DeleteAttachedClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.DeleteAttachedClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_attached_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters server. - """ - return request, metadata - - def post_delete_attached_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_attached_cluster - - Override in a subclass to manipulate the response - after it is returned by the AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_generate_attached_cluster_agent_token(self, request: attached_service.GenerateAttachedClusterAgentTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.GenerateAttachedClusterAgentTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for generate_attached_cluster_agent_token - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters server. - """ - return request, metadata - - def post_generate_attached_cluster_agent_token(self, response: attached_service.GenerateAttachedClusterAgentTokenResponse) -> attached_service.GenerateAttachedClusterAgentTokenResponse: - """Post-rpc interceptor for generate_attached_cluster_agent_token - - Override in a subclass to manipulate the response - after it is returned by the AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_generate_attached_cluster_install_manifest(self, request: attached_service.GenerateAttachedClusterInstallManifestRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.GenerateAttachedClusterInstallManifestRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for generate_attached_cluster_install_manifest - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters server. - """ - return request, metadata - - def post_generate_attached_cluster_install_manifest(self, response: attached_service.GenerateAttachedClusterInstallManifestResponse) -> attached_service.GenerateAttachedClusterInstallManifestResponse: - """Post-rpc interceptor for generate_attached_cluster_install_manifest - - Override in a subclass to manipulate the response - after it is returned by the AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_get_attached_cluster(self, request: attached_service.GetAttachedClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.GetAttachedClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_attached_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters server. - """ - return request, metadata - - def post_get_attached_cluster(self, response: attached_resources.AttachedCluster) -> attached_resources.AttachedCluster: - """Post-rpc interceptor for get_attached_cluster - - Override in a subclass to manipulate the response - after it is returned by the AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_get_attached_server_config(self, request: attached_service.GetAttachedServerConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.GetAttachedServerConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_attached_server_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters server. - """ - return request, metadata - - def post_get_attached_server_config(self, response: attached_resources.AttachedServerConfig) -> attached_resources.AttachedServerConfig: - """Post-rpc interceptor for get_attached_server_config - - Override in a subclass to manipulate the response - after it is returned by the AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_import_attached_cluster(self, request: attached_service.ImportAttachedClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.ImportAttachedClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for import_attached_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters server. - """ - return request, metadata - - def post_import_attached_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_attached_cluster - - Override in a subclass to manipulate the response - after it is returned by the AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_list_attached_clusters(self, request: attached_service.ListAttachedClustersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.ListAttachedClustersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_attached_clusters - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters server. - """ - return request, metadata - - def post_list_attached_clusters(self, response: attached_service.ListAttachedClustersResponse) -> attached_service.ListAttachedClustersResponse: - """Post-rpc interceptor for list_attached_clusters - - Override in a subclass to manipulate the response - after it is returned by the AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_update_attached_cluster(self, request: attached_service.UpdateAttachedClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[attached_service.UpdateAttachedClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_attached_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters server. - """ - return request, metadata - - def post_update_attached_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_attached_cluster - - Override in a subclass to manipulate the response - after it is returned by the AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters 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 AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters 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 AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters 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 AttachedClusters server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the AttachedClusters 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 AttachedClusters server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AttachedClustersRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AttachedClustersRestInterceptor - - -class AttachedClustersRestTransport(_BaseAttachedClustersRestTransport): - """REST backend synchronous transport for AttachedClusters. - - The AttachedClusters API provides a single centrally managed - service to register and manage Anthos attached clusters that run - on customer's owned infrastructure. - - 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 = 'gkemulticloud.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[AttachedClustersRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - 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 AttachedClustersRestInterceptor() - 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 _CreateAttachedCluster(_BaseAttachedClustersRestTransport._BaseCreateAttachedCluster, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.CreateAttachedCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: attached_service.CreateAttachedClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create attached cluster method over HTTP. - - Args: - request (~.attached_service.CreateAttachedClusterRequest): - The request object. Request message for - ``AttachedClusters.CreateAttachedCluster`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAttachedClustersRestTransport._BaseCreateAttachedCluster._get_http_options() - - request, metadata = self._interceptor.pre_create_attached_cluster(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseCreateAttachedCluster._get_transcoded_request(http_options, request) - - body = _BaseAttachedClustersRestTransport._BaseCreateAttachedCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseCreateAttachedCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.CreateAttachedCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "CreateAttachedCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._CreateAttachedCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_attached_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.create_attached_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "CreateAttachedCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteAttachedCluster(_BaseAttachedClustersRestTransport._BaseDeleteAttachedCluster, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.DeleteAttachedCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: attached_service.DeleteAttachedClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete attached cluster method over HTTP. - - Args: - request (~.attached_service.DeleteAttachedClusterRequest): - The request object. Request message for - ``AttachedClusters.DeleteAttachedCluster`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAttachedClustersRestTransport._BaseDeleteAttachedCluster._get_http_options() - - request, metadata = self._interceptor.pre_delete_attached_cluster(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseDeleteAttachedCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseDeleteAttachedCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.DeleteAttachedCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "DeleteAttachedCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._DeleteAttachedCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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_attached_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.delete_attached_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "DeleteAttachedCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GenerateAttachedClusterAgentToken(_BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.GenerateAttachedClusterAgentToken") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: attached_service.GenerateAttachedClusterAgentTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> attached_service.GenerateAttachedClusterAgentTokenResponse: - r"""Call the generate attached cluster - agent token method over HTTP. - - Args: - request (~.attached_service.GenerateAttachedClusterAgentTokenRequest): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.attached_service.GenerateAttachedClusterAgentTokenResponse: - - """ - - http_options = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken._get_http_options() - - request, metadata = self._interceptor.pre_generate_attached_cluster_agent_token(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken._get_transcoded_request(http_options, request) - - body = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.GenerateAttachedClusterAgentToken", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "GenerateAttachedClusterAgentToken", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._GenerateAttachedClusterAgentToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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 = attached_service.GenerateAttachedClusterAgentTokenResponse() - pb_resp = attached_service.GenerateAttachedClusterAgentTokenResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_generate_attached_cluster_agent_token(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = attached_service.GenerateAttachedClusterAgentTokenResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.generate_attached_cluster_agent_token", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "GenerateAttachedClusterAgentToken", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GenerateAttachedClusterInstallManifest(_BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterInstallManifest, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.GenerateAttachedClusterInstallManifest") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: attached_service.GenerateAttachedClusterInstallManifestRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> attached_service.GenerateAttachedClusterInstallManifestResponse: - r"""Call the generate attached cluster - install manifest method over HTTP. - - Args: - request (~.attached_service.GenerateAttachedClusterInstallManifestRequest): - The request object. Request message for - ``AttachedClusters.GenerateAttachedClusterInstallManifest`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.attached_service.GenerateAttachedClusterInstallManifestResponse: - Response message for - ``AttachedClusters.GenerateAttachedClusterInstallManifest`` - method. - - """ - - http_options = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterInstallManifest._get_http_options() - - request, metadata = self._interceptor.pre_generate_attached_cluster_install_manifest(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterInstallManifest._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterInstallManifest._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.GenerateAttachedClusterInstallManifest", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "GenerateAttachedClusterInstallManifest", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._GenerateAttachedClusterInstallManifest._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = attached_service.GenerateAttachedClusterInstallManifestResponse() - pb_resp = attached_service.GenerateAttachedClusterInstallManifestResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_generate_attached_cluster_install_manifest(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = attached_service.GenerateAttachedClusterInstallManifestResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.generate_attached_cluster_install_manifest", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "GenerateAttachedClusterInstallManifest", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAttachedCluster(_BaseAttachedClustersRestTransport._BaseGetAttachedCluster, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.GetAttachedCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: attached_service.GetAttachedClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> attached_resources.AttachedCluster: - r"""Call the get attached cluster method over HTTP. - - Args: - request (~.attached_service.GetAttachedClusterRequest): - The request object. Request message for - ``AttachedClusters.GetAttachedCluster`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.attached_resources.AttachedCluster: - An Anthos cluster running on customer - own infrastructure. - - """ - - http_options = _BaseAttachedClustersRestTransport._BaseGetAttachedCluster._get_http_options() - - request, metadata = self._interceptor.pre_get_attached_cluster(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseGetAttachedCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseGetAttachedCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.GetAttachedCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "GetAttachedCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._GetAttachedCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = attached_resources.AttachedCluster() - pb_resp = attached_resources.AttachedCluster.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_attached_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = attached_resources.AttachedCluster.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.get_attached_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "GetAttachedCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAttachedServerConfig(_BaseAttachedClustersRestTransport._BaseGetAttachedServerConfig, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.GetAttachedServerConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: attached_service.GetAttachedServerConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> attached_resources.AttachedServerConfig: - r"""Call the get attached server - config method over HTTP. - - Args: - request (~.attached_service.GetAttachedServerConfigRequest): - The request object. GetAttachedServerConfigRequest gets - the server config for attached clusters. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.attached_resources.AttachedServerConfig: - AttachedServerConfig provides - information about supported Kubernetes - versions - - """ - - http_options = _BaseAttachedClustersRestTransport._BaseGetAttachedServerConfig._get_http_options() - - request, metadata = self._interceptor.pre_get_attached_server_config(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseGetAttachedServerConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseGetAttachedServerConfig._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.GetAttachedServerConfig", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "GetAttachedServerConfig", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._GetAttachedServerConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = attached_resources.AttachedServerConfig() - pb_resp = attached_resources.AttachedServerConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_attached_server_config(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = attached_resources.AttachedServerConfig.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.get_attached_server_config", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "GetAttachedServerConfig", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ImportAttachedCluster(_BaseAttachedClustersRestTransport._BaseImportAttachedCluster, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.ImportAttachedCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: attached_service.ImportAttachedClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the import attached cluster method over HTTP. - - Args: - request (~.attached_service.ImportAttachedClusterRequest): - The request object. Request message for - ``AttachedClusters.ImportAttachedCluster`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAttachedClustersRestTransport._BaseImportAttachedCluster._get_http_options() - - request, metadata = self._interceptor.pre_import_attached_cluster(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseImportAttachedCluster._get_transcoded_request(http_options, request) - - body = _BaseAttachedClustersRestTransport._BaseImportAttachedCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseImportAttachedCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.ImportAttachedCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "ImportAttachedCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._ImportAttachedCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_import_attached_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.import_attached_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "ImportAttachedCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListAttachedClusters(_BaseAttachedClustersRestTransport._BaseListAttachedClusters, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.ListAttachedClusters") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: attached_service.ListAttachedClustersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> attached_service.ListAttachedClustersResponse: - r"""Call the list attached clusters method over HTTP. - - Args: - request (~.attached_service.ListAttachedClustersRequest): - The request object. Request message for - ``AttachedClusters.ListAttachedClusters`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.attached_service.ListAttachedClustersResponse: - Response message for - ``AttachedClusters.ListAttachedClusters`` method. - - """ - - http_options = _BaseAttachedClustersRestTransport._BaseListAttachedClusters._get_http_options() - - request, metadata = self._interceptor.pre_list_attached_clusters(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseListAttachedClusters._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseListAttachedClusters._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.ListAttachedClusters", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "ListAttachedClusters", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._ListAttachedClusters._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = attached_service.ListAttachedClustersResponse() - pb_resp = attached_service.ListAttachedClustersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_attached_clusters(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = attached_service.ListAttachedClustersResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.list_attached_clusters", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "ListAttachedClusters", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateAttachedCluster(_BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.UpdateAttachedCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: attached_service.UpdateAttachedClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update attached cluster method over HTTP. - - Args: - request (~.attached_service.UpdateAttachedClusterRequest): - The request object. Request message for - ``AttachedClusters.UpdateAttachedCluster`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster._get_http_options() - - request, metadata = self._interceptor.pre_update_attached_cluster(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster._get_transcoded_request(http_options, request) - - body = _BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.UpdateAttachedCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "UpdateAttachedCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._UpdateAttachedCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_attached_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersClient.update_attached_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "UpdateAttachedCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_attached_cluster(self) -> Callable[ - [attached_service.CreateAttachedClusterRequest], - 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._CreateAttachedCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_attached_cluster(self) -> Callable[ - [attached_service.DeleteAttachedClusterRequest], - 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._DeleteAttachedCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_attached_cluster_agent_token(self) -> Callable[ - [attached_service.GenerateAttachedClusterAgentTokenRequest], - attached_service.GenerateAttachedClusterAgentTokenResponse]: - # 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._GenerateAttachedClusterAgentToken(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_attached_cluster_install_manifest(self) -> Callable[ - [attached_service.GenerateAttachedClusterInstallManifestRequest], - attached_service.GenerateAttachedClusterInstallManifestResponse]: - # 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._GenerateAttachedClusterInstallManifest(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_attached_cluster(self) -> Callable[ - [attached_service.GetAttachedClusterRequest], - attached_resources.AttachedCluster]: - # 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._GetAttachedCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_attached_server_config(self) -> Callable[ - [attached_service.GetAttachedServerConfigRequest], - attached_resources.AttachedServerConfig]: - # 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._GetAttachedServerConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_attached_cluster(self) -> Callable[ - [attached_service.ImportAttachedClusterRequest], - 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._ImportAttachedCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_attached_clusters(self) -> Callable[ - [attached_service.ListAttachedClustersRequest], - attached_service.ListAttachedClustersResponse]: - # 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._ListAttachedClusters(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_attached_cluster(self) -> Callable[ - [attached_service.UpdateAttachedClusterRequest], - 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._UpdateAttachedCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseAttachedClustersRestTransport._BaseCancelOperation, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseAttachedClustersRestTransport._BaseCancelOperation._get_http_options() - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseAttachedClustersRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.CancelOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "CancelOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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(_BaseAttachedClustersRestTransport._BaseDeleteOperation, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseAttachedClustersRestTransport._BaseDeleteOperation._get_http_options() - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.DeleteOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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(_BaseAttachedClustersRestTransport._BaseGetOperation, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseAttachedClustersRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.GetOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersAsyncClient.GetOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "GetOperation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseAttachedClustersRestTransport._BaseListOperations, AttachedClustersRestStub): - def __hash__(self): - return hash("AttachedClustersRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseAttachedClustersRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseAttachedClustersRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAttachedClustersRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AttachedClustersClient.ListOperations", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AttachedClustersRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AttachedClustersAsyncClient.ListOperations", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "rpcName": "ListOperations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AttachedClustersRestTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest_base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest_base.py deleted file mode 100644 index 5ee95d700095..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/attached_clusters/transports/rest_base.py +++ /dev/null @@ -1,562 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import AttachedClustersTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.gke_multicloud_v1.types import attached_resources -from google.cloud.gke_multicloud_v1.types import attached_service -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseAttachedClustersRestTransport(AttachedClustersTransport): - """Base REST backend transport for AttachedClusters. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - 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 = 'gkemulticloud.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[Any]): 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. - 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 - 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 - ) - - class _BaseCreateAttachedCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "attachedClusterId" : "", } - - @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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/attachedClusters', - 'body': 'attached_cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = attached_service.CreateAttachedClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAttachedClustersRestTransport._BaseCreateAttachedCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseDeleteAttachedCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/attachedClusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = attached_service.DeleteAttachedClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAttachedClustersRestTransport._BaseDeleteAttachedCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGenerateAttachedClusterAgentToken: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{attached_cluster=projects/*/locations/*/attachedClusters/*}:generateAttachedClusterAgentToken', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = attached_service.GenerateAttachedClusterAgentTokenRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterAgentToken._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGenerateAttachedClusterInstallManifest: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "attachedClusterId" : "", "platformVersion" : "", } - - @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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}:generateAttachedClusterInstallManifest', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = attached_service.GenerateAttachedClusterInstallManifestRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAttachedClustersRestTransport._BaseGenerateAttachedClusterInstallManifest._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAttachedCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/attachedClusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = attached_service.GetAttachedClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAttachedClustersRestTransport._BaseGetAttachedCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAttachedServerConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/attachedServerConfig}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = attached_service.GetAttachedServerConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAttachedClustersRestTransport._BaseGetAttachedServerConfig._get_unset_required_fields(query_params)) - - return query_params - - class _BaseImportAttachedCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/attachedClusters:import', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = attached_service.ImportAttachedClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAttachedClustersRestTransport._BaseImportAttachedCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseListAttachedClusters: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/attachedClusters', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = attached_service.ListAttachedClustersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAttachedClustersRestTransport._BaseListAttachedClusters._get_unset_required_fields(query_params)) - - return query_params - - class _BaseUpdateAttachedCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{attached_cluster.name=projects/*/locations/*/attachedClusters/*}', - 'body': 'attached_cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = attached_service.UpdateAttachedClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAttachedClustersRestTransport._BaseUpdateAttachedCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseCancelOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseDeleteOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListOperations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseAttachedClustersRestTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/__init__.py deleted file mode 100644 index 123c91fd9705..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AwsClustersClient -from .async_client import AwsClustersAsyncClient - -__all__ = ( - 'AwsClustersClient', - 'AwsClustersAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/async_client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/async_client.py deleted file mode 100644 index 0a7ee98c245a..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/async_client.py +++ /dev/null @@ -1,2561 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.gke_multicloud_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.gke_multicloud_v1.services.aws_clusters import pagers -from google.cloud.gke_multicloud_v1.types import aws_resources -from google.cloud.gke_multicloud_v1.types import aws_service -from google.cloud.gke_multicloud_v1.types import common_resources -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import AwsClustersTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AwsClustersGrpcAsyncIOTransport -from .client import AwsClustersClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class AwsClustersAsyncClient: - """The AwsClusters API provides a single centrally managed - service to create and manage Anthos clusters that run on AWS - infrastructure. - """ - - _client: AwsClustersClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AwsClustersClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AwsClustersClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AwsClustersClient._DEFAULT_UNIVERSE - - aws_cluster_path = staticmethod(AwsClustersClient.aws_cluster_path) - parse_aws_cluster_path = staticmethod(AwsClustersClient.parse_aws_cluster_path) - aws_node_pool_path = staticmethod(AwsClustersClient.aws_node_pool_path) - parse_aws_node_pool_path = staticmethod(AwsClustersClient.parse_aws_node_pool_path) - aws_server_config_path = staticmethod(AwsClustersClient.aws_server_config_path) - parse_aws_server_config_path = staticmethod(AwsClustersClient.parse_aws_server_config_path) - common_billing_account_path = staticmethod(AwsClustersClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AwsClustersClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AwsClustersClient.common_folder_path) - parse_common_folder_path = staticmethod(AwsClustersClient.parse_common_folder_path) - common_organization_path = staticmethod(AwsClustersClient.common_organization_path) - parse_common_organization_path = staticmethod(AwsClustersClient.parse_common_organization_path) - common_project_path = staticmethod(AwsClustersClient.common_project_path) - parse_common_project_path = staticmethod(AwsClustersClient.parse_common_project_path) - common_location_path = staticmethod(AwsClustersClient.common_location_path) - parse_common_location_path = staticmethod(AwsClustersClient.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: - AwsClustersAsyncClient: The constructed client. - """ - return AwsClustersClient.from_service_account_info.__func__(AwsClustersAsyncClient, 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: - AwsClustersAsyncClient: The constructed client. - """ - return AwsClustersClient.from_service_account_file.__func__(AwsClustersAsyncClient, 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 AwsClustersClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AwsClustersTransport: - """Returns the transport used by the client instance. - - Returns: - AwsClustersTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = AwsClustersClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AwsClustersTransport, Callable[..., AwsClustersTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the aws clusters async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AwsClustersTransport,Callable[..., AwsClustersTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the AwsClustersTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = AwsClustersClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.gkemulticloud_v1.AwsClustersAsyncClient`.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "credentialsType": None, - } - ) - - async def create_aws_cluster(self, - request: Optional[Union[aws_service.CreateAwsClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - aws_cluster: Optional[aws_resources.AwsCluster] = None, - aws_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource - on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_create_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - aws_cluster = gke_multicloud_v1.AwsCluster() - aws_cluster.networking.vpc_id = "vpc_id_value" - aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - aws_cluster.aws_region = "aws_region_value" - aws_cluster.control_plane.version = "version_value" - aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] - aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" - aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" - aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAwsClusterRequest( - parent="parent_value", - aws_cluster=aws_cluster, - aws_cluster_id="aws_cluster_id_value", - ) - - # Make the request - operation = client.create_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAwsClusterRequest, dict]]): - The request object. Request message for ``AwsClusters.CreateAwsCluster`` - method. - parent (:class:`str`): - Required. The parent location where this - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - aws_cluster (:class:`google.cloud.gke_multicloud_v1.types.AwsCluster`): - Required. The specification of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - to create. - - This corresponds to the ``aws_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - aws_cluster_id (:class:`str`): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource name formatted as - ``projects//locations//awsClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``aws_cluster_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AwsCluster` - An Anthos cluster running on AWS. - - """ - # 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, aws_cluster, aws_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.CreateAwsClusterRequest): - request = aws_service.CreateAwsClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if aws_cluster is not None: - request.aws_cluster = aws_cluster - if aws_cluster_id is not None: - request.aws_cluster_id = aws_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_aws_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - aws_resources.AwsCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_aws_cluster(self, - request: Optional[Union[aws_service.UpdateAwsClusterRequest, dict]] = None, - *, - aws_cluster: Optional[aws_resources.AwsCluster] = 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, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - .. 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 gke_multicloud_v1 - - async def sample_update_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - aws_cluster = gke_multicloud_v1.AwsCluster() - aws_cluster.networking.vpc_id = "vpc_id_value" - aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - aws_cluster.aws_region = "aws_region_value" - aws_cluster.control_plane.version = "version_value" - aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] - aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" - aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" - aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAwsClusterRequest( - aws_cluster=aws_cluster, - ) - - # Make the request - operation = client.update_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.UpdateAwsClusterRequest, dict]]): - The request object. Request message for ``AwsClusters.UpdateAwsCluster`` - method. - aws_cluster (:class:`google.cloud.gke_multicloud_v1.types.AwsCluster`): - Required. The - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource to update. - - This corresponds to the ``aws_cluster`` 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 path - must be supplied in this field. The elements of the - repeated paths field can only include these fields from - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]: - - - ``description``. - - ``annotations``. - - ``control_plane.version``. - - ``authorization.admin_users``. - - ``authorization.admin_groups``. - - ``binary_authorization.evaluation_mode``. - - ``control_plane.aws_services_authentication.role_arn``. - - ``control_plane.aws_services_authentication.role_session_name``. - - ``control_plane.config_encryption.kms_key_arn``. - - ``control_plane.instance_type``. - - ``control_plane.security_group_ids``. - - ``control_plane.proxy_config``. - - ``control_plane.proxy_config.secret_arn``. - - ``control_plane.proxy_config.secret_version``. - - ``control_plane.root_volume.size_gib``. - - ``control_plane.root_volume.volume_type``. - - ``control_plane.root_volume.iops``. - - ``control_plane.root_volume.throughput``. - - ``control_plane.root_volume.kms_key_arn``. - - ``control_plane.ssh_config``. - - ``control_plane.ssh_config.ec2_key_pair``. - - ``control_plane.instance_placement.tenancy``. - - ``control_plane.iam_instance_profile``. - - ``logging_config.component_config.enable_components``. - - ``control_plane.tags``. - - ``monitoring_config.managed_prometheus_config.enabled``. - - ``networking.per_node_pool_sg_rules_disabled``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AwsCluster` - An Anthos cluster running on AWS. - - """ - # 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([aws_cluster, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.UpdateAwsClusterRequest): - request = aws_service.UpdateAwsClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if aws_cluster is not None: - request.aws_cluster = aws_cluster - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_aws_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_cluster.name", request.aws_cluster.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - aws_resources.AwsCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_aws_cluster(self, - request: Optional[Union[aws_service.GetAwsClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_resources.AwsCluster: - r"""Describes a specific - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] 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 gke_multicloud_v1 - - async def sample_get_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_aws_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAwsClusterRequest, dict]]): - The request object. Request message for ``AwsClusters.GetAwsCluster`` - method. - name (:class:`str`): - Required. The name of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource to describe. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AwsCluster: - An Anthos cluster running on AWS. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GetAwsClusterRequest): - request = aws_service.GetAwsClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_aws_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_aws_clusters(self, - request: Optional[Union[aws_service.ListAwsClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAwsClustersAsyncPager: - r"""Lists all [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resources on a given Google Cloud project and region. - - .. 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 gke_multicloud_v1 - - async def sample_list_aws_clusters(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAwsClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_aws_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest, dict]]): - The request object. Request message for ``AwsClusters.ListAwsClusters`` - method. - parent (:class:`str`): - Required. The parent location which owns this collection - of - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsClustersAsyncPager: - Response message for AwsClusters.ListAwsClusters method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.ListAwsClustersRequest): - request = aws_service.ListAwsClustersRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_aws_clusters] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAwsClustersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_aws_cluster(self, - request: Optional[Union[aws_service.DeleteAwsClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a specific - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. - - Fails if the cluster has one or more associated - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_delete_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAwsClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAwsClusterRequest, dict]]): - The request object. Request message for ``AwsClusters.DeleteAwsCluster`` - method. - name (:class:`str`): - Required. The resource name the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - to delete. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.DeleteAwsClusterRequest): - request = aws_service.DeleteAwsClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_aws_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def generate_aws_cluster_agent_token(self, - request: Optional[Union[aws_service.GenerateAwsClusterAgentTokenRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_service.GenerateAwsClusterAgentTokenResponse: - r"""Generates an access token for a cluster agent. - - .. 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 gke_multicloud_v1 - - async def sample_generate_aws_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAwsClusterAgentTokenRequest( - aws_cluster="aws_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = await client.generate_aws_cluster_agent_token(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenRequest, dict]]): - The request object. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenResponse: - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GenerateAwsClusterAgentTokenRequest): - request = aws_service.GenerateAwsClusterAgentTokenRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_aws_cluster_agent_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_cluster", request.aws_cluster), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def generate_aws_access_token(self, - request: Optional[Union[aws_service.GenerateAwsAccessTokenRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_service.GenerateAwsAccessTokenResponse: - r"""Generates a short-lived access token to authenticate to a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] 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 gke_multicloud_v1 - - async def sample_generate_aws_access_token(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAwsAccessTokenRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = await client.generate_aws_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenRequest, dict]]): - The request object. Request message for - ``AwsClusters.GenerateAwsAccessToken`` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenResponse: - Response message for AwsClusters.GenerateAwsAccessToken - method. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GenerateAwsAccessTokenRequest): - request = aws_service.GenerateAwsAccessTokenRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_aws_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_cluster", request.aws_cluster), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_aws_node_pool(self, - request: Optional[Union[aws_service.CreateAwsNodePoolRequest, dict]] = None, - *, - parent: Optional[str] = None, - aws_node_pool: Optional[aws_resources.AwsNodePool] = None, - aws_node_pool_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool], - attached to a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_create_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - aws_node_pool = gke_multicloud_v1.AwsNodePool() - aws_node_pool.version = "version_value" - aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" - aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_node_pool.autoscaling.min_node_count = 1489 - aws_node_pool.autoscaling.max_node_count = 1491 - aws_node_pool.subnet_id = "subnet_id_value" - aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.CreateAwsNodePoolRequest( - parent="parent_value", - aws_node_pool=aws_node_pool, - aws_node_pool_id="aws_node_pool_id_value", - ) - - # Make the request - operation = client.create_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAwsNodePoolRequest, dict]]): - The request object. Response message for ``AwsClusters.CreateAwsNodePool`` - method. - parent (:class:`str`): - Required. The - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource where this node pool will be created. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - aws_node_pool (:class:`google.cloud.gke_multicloud_v1.types.AwsNodePool`): - Required. The specification of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - to create. - - This corresponds to the ``aws_node_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - aws_node_pool_id (:class:`str`): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource name formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``aws_node_pool_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AwsNodePool` - An Anthos node pool running on AWS. - - """ - # 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, aws_node_pool, aws_node_pool_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.CreateAwsNodePoolRequest): - request = aws_service.CreateAwsNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if aws_node_pool is not None: - request.aws_node_pool = aws_node_pool - if aws_node_pool_id is not None: - request.aws_node_pool_id = aws_node_pool_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_aws_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - aws_resources.AwsNodePool, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_aws_node_pool(self, - request: Optional[Union[aws_service.UpdateAwsNodePoolRequest, dict]] = None, - *, - aws_node_pool: Optional[aws_resources.AwsNodePool] = 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, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. - - .. 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 gke_multicloud_v1 - - async def sample_update_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - aws_node_pool = gke_multicloud_v1.AwsNodePool() - aws_node_pool.version = "version_value" - aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" - aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_node_pool.autoscaling.min_node_count = 1489 - aws_node_pool.autoscaling.max_node_count = 1491 - aws_node_pool.subnet_id = "subnet_id_value" - aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.UpdateAwsNodePoolRequest( - aws_node_pool=aws_node_pool, - ) - - # Make the request - operation = client.update_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.UpdateAwsNodePoolRequest, dict]]): - The request object. Request message for ``AwsClusters.UpdateAwsNodePool`` - method. - aws_node_pool (:class:`google.cloud.gke_multicloud_v1.types.AwsNodePool`): - Required. The - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource to update. - - This corresponds to the ``aws_node_pool`` 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 path - must be supplied in this field. The elements of the - repeated paths field can only include these fields from - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]: - - - ``annotations``. - - ``version``. - - ``autoscaling.min_node_count``. - - ``autoscaling.max_node_count``. - - ``config.config_encryption.kms_key_arn``. - - ``config.security_group_ids``. - - ``config.root_volume.iops``. - - ``config.root_volume.throughput``. - - ``config.root_volume.kms_key_arn``. - - ``config.root_volume.volume_type``. - - ``config.root_volume.size_gib``. - - ``config.proxy_config``. - - ``config.proxy_config.secret_arn``. - - ``config.proxy_config.secret_version``. - - ``config.ssh_config``. - - ``config.ssh_config.ec2_key_pair``. - - ``config.instance_placement.tenancy``. - - ``config.iam_instance_profile``. - - ``config.labels``. - - ``config.tags``. - - ``config.autoscaling_metrics_collection``. - - ``config.autoscaling_metrics_collection.granularity``. - - ``config.autoscaling_metrics_collection.metrics``. - - ``config.instance_type``. - - ``management.auto_repair``. - - ``management``. - - ``update_settings``. - - ``update_settings.surge_settings``. - - ``update_settings.surge_settings.max_surge``. - - ``update_settings.surge_settings.max_unavailable``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AwsNodePool` - An Anthos node pool running on AWS. - - """ - # 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([aws_node_pool, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.UpdateAwsNodePoolRequest): - request = aws_service.UpdateAwsNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if aws_node_pool is not None: - request.aws_node_pool = aws_node_pool - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_aws_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_node_pool.name", request.aws_node_pool.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - aws_resources.AwsNodePool, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def rollback_aws_node_pool_update(self, - request: Optional[Union[aws_service.RollbackAwsNodePoolUpdateRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Rolls back a previously aborted or failed - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] update - request. Makes no changes if the last update request - successfully finished. If an update request is in progress, you - cannot rollback the update. You must first cancel or let it - finish unsuccessfully before you can rollback. - - .. 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 gke_multicloud_v1 - - async def sample_rollback_aws_node_pool_update(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.RollbackAwsNodePoolUpdateRequest( - name="name_value", - ) - - # Make the request - operation = client.rollback_aws_node_pool_update(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.RollbackAwsNodePoolUpdateRequest, dict]]): - The request object. Request message for - ``AwsClusters.RollbackAwsNodePoolUpdate`` method. - name (:class:`str`): - Required. The name of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource to rollback. - - ``AwsNodePool`` names are formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AwsNodePool` - An Anthos node pool running on AWS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.RollbackAwsNodePoolUpdateRequest): - request = aws_service.RollbackAwsNodePoolUpdateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.rollback_aws_node_pool_update] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - aws_resources.AwsNodePool, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_aws_node_pool(self, - request: Optional[Union[aws_service.GetAwsNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_resources.AwsNodePool: - r"""Describes a specific - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - 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 gke_multicloud_v1 - - async def sample_get_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsNodePoolRequest( - name="name_value", - ) - - # Make the request - response = await client.get_aws_node_pool(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAwsNodePoolRequest, dict]]): - The request object. Request message for ``AwsClusters.GetAwsNodePool`` - method. - name (:class:`str`): - Required. The name of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource to describe. - - ``AwsNodePool`` names are formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AwsNodePool: - An Anthos node pool running on AWS. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GetAwsNodePoolRequest): - request = aws_service.GetAwsNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_aws_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_aws_node_pools(self, - request: Optional[Union[aws_service.ListAwsNodePoolsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAwsNodePoolsAsyncPager: - r"""Lists all - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources on a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - .. 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 gke_multicloud_v1 - - async def sample_list_aws_node_pools(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAwsNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_aws_node_pools(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest, dict]]): - The request object. Request message for ``AwsClusters.ListAwsNodePools`` - method. - parent (:class:`str`): - Required. The parent ``AwsCluster`` which owns this - collection of - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsNodePoolsAsyncPager: - Response message for AwsClusters.ListAwsNodePools - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.ListAwsNodePoolsRequest): - request = aws_service.ListAwsNodePoolsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_aws_node_pools] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAwsNodePoolsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_aws_node_pool(self, - request: Optional[Union[aws_service.DeleteAwsNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a specific - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_delete_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAwsNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAwsNodePoolRequest, dict]]): - The request object. Request message for ``AwsClusters.DeleteAwsNodePool`` - method. - name (:class:`str`): - Required. The resource name the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - to delete. - - ``AwsNodePool`` names are formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.DeleteAwsNodePoolRequest): - request = aws_service.DeleteAwsNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_aws_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_aws_open_id_config(self, - request: Optional[Union[aws_service.GetAwsOpenIdConfigRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_resources.AwsOpenIdConfig: - r"""Gets the OIDC discovery document for the cluster. See the - `OpenID Connect Discovery 1.0 - specification `__ - for details. - - .. 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 gke_multicloud_v1 - - async def sample_get_aws_open_id_config(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsOpenIdConfigRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = await client.get_aws_open_id_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAwsOpenIdConfigRequest, dict]]): - The request object. GetAwsOpenIdConfigRequest gets the - OIDC discovery document for the cluster. - See the OpenID Connect Discovery 1.0 - specification for details. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AwsOpenIdConfig: - AwsOpenIdConfig is an OIDC discovery - document for the cluster. See the OpenID - Connect Discovery 1.0 specification for - details. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GetAwsOpenIdConfigRequest): - request = aws_service.GetAwsOpenIdConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_aws_open_id_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_cluster", request.aws_cluster), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_aws_json_web_keys(self, - request: Optional[Union[aws_service.GetAwsJsonWebKeysRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_resources.AwsJsonWebKeys: - r"""Gets the public component of the cluster signing keys - in JSON Web Key format. - - .. 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 gke_multicloud_v1 - - async def sample_get_aws_json_web_keys(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsJsonWebKeysRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = await client.get_aws_json_web_keys(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAwsJsonWebKeysRequest, dict]]): - The request object. GetAwsJsonWebKeysRequest gets the public component of - the keys used by the cluster to sign token requests. - This will be the jwks_uri for the discover document - returned by getOpenIDConfig. See the OpenID Connect - Discovery 1.0 specification for details. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AwsJsonWebKeys: - AwsJsonWebKeys is a valid JSON Web - Key Set as specififed in RFC 7517. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GetAwsJsonWebKeysRequest): - request = aws_service.GetAwsJsonWebKeysRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_aws_json_web_keys] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_cluster", request.aws_cluster), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_aws_server_config(self, - request: Optional[Union[aws_service.GetAwsServerConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_resources.AwsServerConfig: - r"""Returns information, such as supported AWS regions - and Kubernetes versions, on a given Google Cloud - 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 gke_multicloud_v1 - - async def sample_get_aws_server_config(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsServerConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_aws_server_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAwsServerConfigRequest, dict]]): - The request object. GetAwsServerConfigRequest gets the - server config of GKE cluster on AWS. - name (:class:`str`): - Required. The name of the - [AwsServerConfig][google.cloud.gkemulticloud.v1.AwsServerConfig] - resource to describe. - - ``AwsServerConfig`` names are formatted as - ``projects//locations//awsServerConfig``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AwsServerConfig: - AwsServerConfig is the configuration - of GKE cluster on AWS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GetAwsServerConfigRequest): - request = aws_service.GetAwsServerConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_aws_server_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_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, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.list_operations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def 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, Union[str, bytes]]] = (), - ) -> 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_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.delete_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - 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, Union[str, bytes]]] = (), - ) -> 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_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.cancel_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self) -> "AwsClustersAsyncClient": - 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__ = ( - "AwsClustersAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/client.py deleted file mode 100644 index 6d1fbb83b1d7..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/client.py +++ /dev/null @@ -1,2903 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.gke_multicloud_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.gke_multicloud_v1.services.aws_clusters import pagers -from google.cloud.gke_multicloud_v1.types import aws_resources -from google.cloud.gke_multicloud_v1.types import aws_service -from google.cloud.gke_multicloud_v1.types import common_resources -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import AwsClustersTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AwsClustersGrpcTransport -from .transports.grpc_asyncio import AwsClustersGrpcAsyncIOTransport -from .transports.rest import AwsClustersRestTransport - - -class AwsClustersClientMeta(type): - """Metaclass for the AwsClusters 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[AwsClustersTransport]] - _transport_registry["grpc"] = AwsClustersGrpcTransport - _transport_registry["grpc_asyncio"] = AwsClustersGrpcAsyncIOTransport - _transport_registry["rest"] = AwsClustersRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AwsClustersTransport]: - """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 AwsClustersClient(metaclass=AwsClustersClientMeta): - """The AwsClusters API provides a single centrally managed - service to create and manage Anthos clusters that run on AWS - infrastructure. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "gkemulticloud.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "gkemulticloud.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AwsClustersClient: 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: - AwsClustersClient: 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) -> AwsClustersTransport: - """Returns the transport used by the client instance. - - Returns: - AwsClustersTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def aws_cluster_path(project: str,location: str,aws_cluster: str,) -> str: - """Returns a fully-qualified aws_cluster string.""" - return "projects/{project}/locations/{location}/awsClusters/{aws_cluster}".format(project=project, location=location, aws_cluster=aws_cluster, ) - - @staticmethod - def parse_aws_cluster_path(path: str) -> Dict[str,str]: - """Parses a aws_cluster path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/awsClusters/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def aws_node_pool_path(project: str,location: str,aws_cluster: str,aws_node_pool: str,) -> str: - """Returns a fully-qualified aws_node_pool string.""" - return "projects/{project}/locations/{location}/awsClusters/{aws_cluster}/awsNodePools/{aws_node_pool}".format(project=project, location=location, aws_cluster=aws_cluster, aws_node_pool=aws_node_pool, ) - - @staticmethod - def parse_aws_node_pool_path(path: str) -> Dict[str,str]: - """Parses a aws_node_pool path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/awsClusters/(?P.+?)/awsNodePools/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def aws_server_config_path(project: str,location: str,) -> str: - """Returns a fully-qualified aws_server_config string.""" - return "projects/{project}/locations/{location}/awsServerConfig".format(project=project, location=location, ) - - @staticmethod - def parse_aws_server_config_path(path: str) -> Dict[str,str]: - """Parses a aws_server_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/awsServerConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = AwsClustersClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AwsClustersClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = AwsClustersClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AwsClustersTransport, Callable[..., AwsClustersTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the aws clusters client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AwsClustersTransport,Callable[..., AwsClustersTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the AwsClustersTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AwsClustersClient._read_environment_variables() - self._client_cert_source = AwsClustersClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AwsClustersClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, AwsClustersTransport) - if transport_provided: - # transport is a AwsClustersTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(AwsClustersTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AwsClustersClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[AwsClustersTransport], Callable[..., AwsClustersTransport]] = ( - AwsClustersClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AwsClustersTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.gkemulticloud_v1.AwsClustersClient`.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "credentialsType": None, - } - ) - - def create_aws_cluster(self, - request: Optional[Union[aws_service.CreateAwsClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - aws_cluster: Optional[aws_resources.AwsCluster] = None, - aws_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource - on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_create_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - aws_cluster = gke_multicloud_v1.AwsCluster() - aws_cluster.networking.vpc_id = "vpc_id_value" - aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - aws_cluster.aws_region = "aws_region_value" - aws_cluster.control_plane.version = "version_value" - aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] - aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" - aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" - aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAwsClusterRequest( - parent="parent_value", - aws_cluster=aws_cluster, - aws_cluster_id="aws_cluster_id_value", - ) - - # Make the request - operation = client.create_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.CreateAwsClusterRequest, dict]): - The request object. Request message for ``AwsClusters.CreateAwsCluster`` - method. - parent (str): - Required. The parent location where this - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - aws_cluster (google.cloud.gke_multicloud_v1.types.AwsCluster): - Required. The specification of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - to create. - - This corresponds to the ``aws_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - aws_cluster_id (str): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource name formatted as - ``projects//locations//awsClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``aws_cluster_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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AwsCluster` - An Anthos cluster running on AWS. - - """ - # 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, aws_cluster, aws_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.CreateAwsClusterRequest): - request = aws_service.CreateAwsClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if aws_cluster is not None: - request.aws_cluster = aws_cluster - if aws_cluster_id is not None: - request.aws_cluster_id = aws_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_aws_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - aws_resources.AwsCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_aws_cluster(self, - request: Optional[Union[aws_service.UpdateAwsClusterRequest, dict]] = None, - *, - aws_cluster: Optional[aws_resources.AwsCluster] = 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, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates an - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - .. 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 gke_multicloud_v1 - - def sample_update_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - aws_cluster = gke_multicloud_v1.AwsCluster() - aws_cluster.networking.vpc_id = "vpc_id_value" - aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - aws_cluster.aws_region = "aws_region_value" - aws_cluster.control_plane.version = "version_value" - aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] - aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" - aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" - aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAwsClusterRequest( - aws_cluster=aws_cluster, - ) - - # Make the request - operation = client.update_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.UpdateAwsClusterRequest, dict]): - The request object. Request message for ``AwsClusters.UpdateAwsCluster`` - method. - aws_cluster (google.cloud.gke_multicloud_v1.types.AwsCluster): - Required. The - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource to update. - - This corresponds to the ``aws_cluster`` 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 path - must be supplied in this field. The elements of the - repeated paths field can only include these fields from - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]: - - - ``description``. - - ``annotations``. - - ``control_plane.version``. - - ``authorization.admin_users``. - - ``authorization.admin_groups``. - - ``binary_authorization.evaluation_mode``. - - ``control_plane.aws_services_authentication.role_arn``. - - ``control_plane.aws_services_authentication.role_session_name``. - - ``control_plane.config_encryption.kms_key_arn``. - - ``control_plane.instance_type``. - - ``control_plane.security_group_ids``. - - ``control_plane.proxy_config``. - - ``control_plane.proxy_config.secret_arn``. - - ``control_plane.proxy_config.secret_version``. - - ``control_plane.root_volume.size_gib``. - - ``control_plane.root_volume.volume_type``. - - ``control_plane.root_volume.iops``. - - ``control_plane.root_volume.throughput``. - - ``control_plane.root_volume.kms_key_arn``. - - ``control_plane.ssh_config``. - - ``control_plane.ssh_config.ec2_key_pair``. - - ``control_plane.instance_placement.tenancy``. - - ``control_plane.iam_instance_profile``. - - ``logging_config.component_config.enable_components``. - - ``control_plane.tags``. - - ``monitoring_config.managed_prometheus_config.enabled``. - - ``networking.per_node_pool_sg_rules_disabled``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AwsCluster` - An Anthos cluster running on AWS. - - """ - # 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([aws_cluster, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.UpdateAwsClusterRequest): - request = aws_service.UpdateAwsClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if aws_cluster is not None: - request.aws_cluster = aws_cluster - 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_aws_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_cluster.name", request.aws_cluster.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - aws_resources.AwsCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_aws_cluster(self, - request: Optional[Union[aws_service.GetAwsClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_resources.AwsCluster: - r"""Describes a specific - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] 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 gke_multicloud_v1 - - def sample_get_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_aws_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAwsClusterRequest, dict]): - The request object. Request message for ``AwsClusters.GetAwsCluster`` - method. - name (str): - Required. The name of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource to describe. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AwsCluster: - An Anthos cluster running on AWS. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GetAwsClusterRequest): - request = aws_service.GetAwsClusterRequest(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_aws_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_aws_clusters(self, - request: Optional[Union[aws_service.ListAwsClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAwsClustersPager: - r"""Lists all [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resources on a given Google Cloud project and region. - - .. 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 gke_multicloud_v1 - - def sample_list_aws_clusters(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAwsClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_aws_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest, dict]): - The request object. Request message for ``AwsClusters.ListAwsClusters`` - method. - parent (str): - Required. The parent location which owns this collection - of - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsClustersPager: - Response message for AwsClusters.ListAwsClusters method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.ListAwsClustersRequest): - request = aws_service.ListAwsClustersRequest(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_aws_clusters] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAwsClustersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_aws_cluster(self, - request: Optional[Union[aws_service.DeleteAwsClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a specific - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. - - Fails if the cluster has one or more associated - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_delete_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAwsClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.DeleteAwsClusterRequest, dict]): - The request object. Request message for ``AwsClusters.DeleteAwsCluster`` - method. - name (str): - Required. The resource name the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - to delete. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.DeleteAwsClusterRequest): - request = aws_service.DeleteAwsClusterRequest(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_aws_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def generate_aws_cluster_agent_token(self, - request: Optional[Union[aws_service.GenerateAwsClusterAgentTokenRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_service.GenerateAwsClusterAgentTokenResponse: - r"""Generates an access token for a cluster agent. - - .. 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 gke_multicloud_v1 - - def sample_generate_aws_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAwsClusterAgentTokenRequest( - aws_cluster="aws_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = client.generate_aws_cluster_agent_token(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenRequest, dict]): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenResponse: - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GenerateAwsClusterAgentTokenRequest): - request = aws_service.GenerateAwsClusterAgentTokenRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_aws_cluster_agent_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_cluster", request.aws_cluster), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_aws_access_token(self, - request: Optional[Union[aws_service.GenerateAwsAccessTokenRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_service.GenerateAwsAccessTokenResponse: - r"""Generates a short-lived access token to authenticate to a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] 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 gke_multicloud_v1 - - def sample_generate_aws_access_token(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAwsAccessTokenRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = client.generate_aws_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenRequest, dict]): - The request object. Request message for - ``AwsClusters.GenerateAwsAccessToken`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenResponse: - Response message for AwsClusters.GenerateAwsAccessToken - method. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GenerateAwsAccessTokenRequest): - request = aws_service.GenerateAwsAccessTokenRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_aws_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_cluster", request.aws_cluster), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_aws_node_pool(self, - request: Optional[Union[aws_service.CreateAwsNodePoolRequest, dict]] = None, - *, - parent: Optional[str] = None, - aws_node_pool: Optional[aws_resources.AwsNodePool] = None, - aws_node_pool_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool], - attached to a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_create_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - aws_node_pool = gke_multicloud_v1.AwsNodePool() - aws_node_pool.version = "version_value" - aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" - aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_node_pool.autoscaling.min_node_count = 1489 - aws_node_pool.autoscaling.max_node_count = 1491 - aws_node_pool.subnet_id = "subnet_id_value" - aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.CreateAwsNodePoolRequest( - parent="parent_value", - aws_node_pool=aws_node_pool, - aws_node_pool_id="aws_node_pool_id_value", - ) - - # Make the request - operation = client.create_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.CreateAwsNodePoolRequest, dict]): - The request object. Response message for ``AwsClusters.CreateAwsNodePool`` - method. - parent (str): - Required. The - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource where this node pool will be created. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - aws_node_pool (google.cloud.gke_multicloud_v1.types.AwsNodePool): - Required. The specification of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - to create. - - This corresponds to the ``aws_node_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - aws_node_pool_id (str): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource name formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``aws_node_pool_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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AwsNodePool` - An Anthos node pool running on AWS. - - """ - # 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, aws_node_pool, aws_node_pool_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.CreateAwsNodePoolRequest): - request = aws_service.CreateAwsNodePoolRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if aws_node_pool is not None: - request.aws_node_pool = aws_node_pool - if aws_node_pool_id is not None: - request.aws_node_pool_id = aws_node_pool_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_aws_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - aws_resources.AwsNodePool, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_aws_node_pool(self, - request: Optional[Union[aws_service.UpdateAwsNodePoolRequest, dict]] = None, - *, - aws_node_pool: Optional[aws_resources.AwsNodePool] = 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, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates an - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. - - .. 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 gke_multicloud_v1 - - def sample_update_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - aws_node_pool = gke_multicloud_v1.AwsNodePool() - aws_node_pool.version = "version_value" - aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" - aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_node_pool.autoscaling.min_node_count = 1489 - aws_node_pool.autoscaling.max_node_count = 1491 - aws_node_pool.subnet_id = "subnet_id_value" - aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.UpdateAwsNodePoolRequest( - aws_node_pool=aws_node_pool, - ) - - # Make the request - operation = client.update_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.UpdateAwsNodePoolRequest, dict]): - The request object. Request message for ``AwsClusters.UpdateAwsNodePool`` - method. - aws_node_pool (google.cloud.gke_multicloud_v1.types.AwsNodePool): - Required. The - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource to update. - - This corresponds to the ``aws_node_pool`` 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 path - must be supplied in this field. The elements of the - repeated paths field can only include these fields from - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]: - - - ``annotations``. - - ``version``. - - ``autoscaling.min_node_count``. - - ``autoscaling.max_node_count``. - - ``config.config_encryption.kms_key_arn``. - - ``config.security_group_ids``. - - ``config.root_volume.iops``. - - ``config.root_volume.throughput``. - - ``config.root_volume.kms_key_arn``. - - ``config.root_volume.volume_type``. - - ``config.root_volume.size_gib``. - - ``config.proxy_config``. - - ``config.proxy_config.secret_arn``. - - ``config.proxy_config.secret_version``. - - ``config.ssh_config``. - - ``config.ssh_config.ec2_key_pair``. - - ``config.instance_placement.tenancy``. - - ``config.iam_instance_profile``. - - ``config.labels``. - - ``config.tags``. - - ``config.autoscaling_metrics_collection``. - - ``config.autoscaling_metrics_collection.granularity``. - - ``config.autoscaling_metrics_collection.metrics``. - - ``config.instance_type``. - - ``management.auto_repair``. - - ``management``. - - ``update_settings``. - - ``update_settings.surge_settings``. - - ``update_settings.surge_settings.max_surge``. - - ``update_settings.surge_settings.max_unavailable``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AwsNodePool` - An Anthos node pool running on AWS. - - """ - # 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([aws_node_pool, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.UpdateAwsNodePoolRequest): - request = aws_service.UpdateAwsNodePoolRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if aws_node_pool is not None: - request.aws_node_pool = aws_node_pool - 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_aws_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_node_pool.name", request.aws_node_pool.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - aws_resources.AwsNodePool, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def rollback_aws_node_pool_update(self, - request: Optional[Union[aws_service.RollbackAwsNodePoolUpdateRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Rolls back a previously aborted or failed - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] update - request. Makes no changes if the last update request - successfully finished. If an update request is in progress, you - cannot rollback the update. You must first cancel or let it - finish unsuccessfully before you can rollback. - - .. 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 gke_multicloud_v1 - - def sample_rollback_aws_node_pool_update(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.RollbackAwsNodePoolUpdateRequest( - name="name_value", - ) - - # Make the request - operation = client.rollback_aws_node_pool_update(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.RollbackAwsNodePoolUpdateRequest, dict]): - The request object. Request message for - ``AwsClusters.RollbackAwsNodePoolUpdate`` method. - name (str): - Required. The name of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource to rollback. - - ``AwsNodePool`` names are formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AwsNodePool` - An Anthos node pool running on AWS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.RollbackAwsNodePoolUpdateRequest): - request = aws_service.RollbackAwsNodePoolUpdateRequest(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.rollback_aws_node_pool_update] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - aws_resources.AwsNodePool, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_aws_node_pool(self, - request: Optional[Union[aws_service.GetAwsNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_resources.AwsNodePool: - r"""Describes a specific - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - 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 gke_multicloud_v1 - - def sample_get_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsNodePoolRequest( - name="name_value", - ) - - # Make the request - response = client.get_aws_node_pool(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAwsNodePoolRequest, dict]): - The request object. Request message for ``AwsClusters.GetAwsNodePool`` - method. - name (str): - Required. The name of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource to describe. - - ``AwsNodePool`` names are formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AwsNodePool: - An Anthos node pool running on AWS. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GetAwsNodePoolRequest): - request = aws_service.GetAwsNodePoolRequest(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_aws_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_aws_node_pools(self, - request: Optional[Union[aws_service.ListAwsNodePoolsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAwsNodePoolsPager: - r"""Lists all - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources on a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - .. 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 gke_multicloud_v1 - - def sample_list_aws_node_pools(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAwsNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_aws_node_pools(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest, dict]): - The request object. Request message for ``AwsClusters.ListAwsNodePools`` - method. - parent (str): - Required. The parent ``AwsCluster`` which owns this - collection of - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsNodePoolsPager: - Response message for AwsClusters.ListAwsNodePools - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.ListAwsNodePoolsRequest): - request = aws_service.ListAwsNodePoolsRequest(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_aws_node_pools] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAwsNodePoolsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_aws_node_pool(self, - request: Optional[Union[aws_service.DeleteAwsNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a specific - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_delete_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAwsNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.DeleteAwsNodePoolRequest, dict]): - The request object. Request message for ``AwsClusters.DeleteAwsNodePool`` - method. - name (str): - Required. The resource name the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - to delete. - - ``AwsNodePool`` names are formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.DeleteAwsNodePoolRequest): - request = aws_service.DeleteAwsNodePoolRequest(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_aws_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_aws_open_id_config(self, - request: Optional[Union[aws_service.GetAwsOpenIdConfigRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_resources.AwsOpenIdConfig: - r"""Gets the OIDC discovery document for the cluster. See the - `OpenID Connect Discovery 1.0 - specification `__ - for details. - - .. 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 gke_multicloud_v1 - - def sample_get_aws_open_id_config(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsOpenIdConfigRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = client.get_aws_open_id_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAwsOpenIdConfigRequest, dict]): - The request object. GetAwsOpenIdConfigRequest gets the - OIDC discovery document for the cluster. - See the OpenID Connect Discovery 1.0 - specification for details. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AwsOpenIdConfig: - AwsOpenIdConfig is an OIDC discovery - document for the cluster. See the OpenID - Connect Discovery 1.0 specification for - details. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GetAwsOpenIdConfigRequest): - request = aws_service.GetAwsOpenIdConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_aws_open_id_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_cluster", request.aws_cluster), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_aws_json_web_keys(self, - request: Optional[Union[aws_service.GetAwsJsonWebKeysRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_resources.AwsJsonWebKeys: - r"""Gets the public component of the cluster signing keys - in JSON Web Key format. - - .. 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 gke_multicloud_v1 - - def sample_get_aws_json_web_keys(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsJsonWebKeysRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = client.get_aws_json_web_keys(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAwsJsonWebKeysRequest, dict]): - The request object. GetAwsJsonWebKeysRequest gets the public component of - the keys used by the cluster to sign token requests. - This will be the jwks_uri for the discover document - returned by getOpenIDConfig. See the OpenID Connect - Discovery 1.0 specification for details. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AwsJsonWebKeys: - AwsJsonWebKeys is a valid JSON Web - Key Set as specififed in RFC 7517. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GetAwsJsonWebKeysRequest): - request = aws_service.GetAwsJsonWebKeysRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_aws_json_web_keys] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("aws_cluster", request.aws_cluster), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_aws_server_config(self, - request: Optional[Union[aws_service.GetAwsServerConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> aws_resources.AwsServerConfig: - r"""Returns information, such as supported AWS regions - and Kubernetes versions, on a given Google Cloud - 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 gke_multicloud_v1 - - def sample_get_aws_server_config(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsServerConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_aws_server_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAwsServerConfigRequest, dict]): - The request object. GetAwsServerConfigRequest gets the - server config of GKE cluster on AWS. - name (str): - Required. The name of the - [AwsServerConfig][google.cloud.gkemulticloud.v1.AwsServerConfig] - resource to describe. - - ``AwsServerConfig`` names are formatted as - ``projects//locations//awsServerConfig``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AwsServerConfig: - AwsServerConfig is the configuration - of GKE cluster on AWS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, aws_service.GetAwsServerConfigRequest): - request = aws_service.GetAwsServerConfigRequest(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_aws_server_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AwsClustersClient": - 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, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.list_operations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def 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, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.delete_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - 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, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.cancel_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AwsClustersClient", -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/pagers.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/pagers.py deleted file mode 100644 index 37c279974e69..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/pagers.py +++ /dev/null @@ -1,306 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.cloud.gke_multicloud_v1.types import aws_resources -from google.cloud.gke_multicloud_v1.types import aws_service - - -class ListAwsClustersPager: - """A pager for iterating through ``list_aws_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``aws_clusters`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAwsClusters`` requests and continue to iterate - through the ``aws_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse` - 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[..., aws_service.ListAwsClustersResponse], - request: aws_service.ListAwsClustersRequest, - response: aws_service.ListAwsClustersResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = aws_service.ListAwsClustersRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[aws_service.ListAwsClustersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[aws_resources.AwsCluster]: - for page in self.pages: - yield from page.aws_clusters - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAwsClustersAsyncPager: - """A pager for iterating through ``list_aws_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``aws_clusters`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAwsClusters`` requests and continue to iterate - through the ``aws_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse` - 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[aws_service.ListAwsClustersResponse]], - request: aws_service.ListAwsClustersRequest, - response: aws_service.ListAwsClustersResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAwsClustersResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = aws_service.ListAwsClustersRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[aws_service.ListAwsClustersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[aws_resources.AwsCluster]: - async def async_generator(): - async for page in self.pages: - for response in page.aws_clusters: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAwsNodePoolsPager: - """A pager for iterating through ``list_aws_node_pools`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``aws_node_pools`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAwsNodePools`` requests and continue to iterate - through the ``aws_node_pools`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse` - 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[..., aws_service.ListAwsNodePoolsResponse], - request: aws_service.ListAwsNodePoolsRequest, - response: aws_service.ListAwsNodePoolsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = aws_service.ListAwsNodePoolsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[aws_service.ListAwsNodePoolsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[aws_resources.AwsNodePool]: - for page in self.pages: - yield from page.aws_node_pools - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAwsNodePoolsAsyncPager: - """A pager for iterating through ``list_aws_node_pools`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``aws_node_pools`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAwsNodePools`` requests and continue to iterate - through the ``aws_node_pools`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse` - 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[aws_service.ListAwsNodePoolsResponse]], - request: aws_service.ListAwsNodePoolsRequest, - response: aws_service.ListAwsNodePoolsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = aws_service.ListAwsNodePoolsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[aws_service.ListAwsNodePoolsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[aws_resources.AwsNodePool]: - async def async_generator(): - async for page in self.pages: - for response in page.aws_node_pools: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/README.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/README.rst deleted file mode 100644 index 9e0624faad5d..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AwsClustersTransport` is the ABC for all transports. -- public child `AwsClustersGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AwsClustersGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAwsClustersRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AwsClustersRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/__init__.py deleted file mode 100644 index f9cb58b758a9..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AwsClustersTransport -from .grpc import AwsClustersGrpcTransport -from .grpc_asyncio import AwsClustersGrpcAsyncIOTransport -from .rest import AwsClustersRestTransport -from .rest import AwsClustersRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AwsClustersTransport]] -_transport_registry['grpc'] = AwsClustersGrpcTransport -_transport_registry['grpc_asyncio'] = AwsClustersGrpcAsyncIOTransport -_transport_registry['rest'] = AwsClustersRestTransport - -__all__ = ( - 'AwsClustersTransport', - 'AwsClustersGrpcTransport', - 'AwsClustersGrpcAsyncIOTransport', - 'AwsClustersRestTransport', - 'AwsClustersRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/base.py deleted file mode 100644 index 0497798ba75e..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/base.py +++ /dev/null @@ -1,509 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.gke_multicloud_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.gke_multicloud_v1.types import aws_resources -from google.cloud.gke_multicloud_v1.types import aws_service -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AwsClustersTransport(abc.ABC): - """Abstract transport class for AwsClusters.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'gkemulticloud.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_aws_cluster: gapic_v1.method.wrap_method( - self.create_aws_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_aws_cluster: gapic_v1.method.wrap_method( - self.update_aws_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_aws_cluster: gapic_v1.method.wrap_method( - self.get_aws_cluster, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_aws_clusters: gapic_v1.method.wrap_method( - self.list_aws_clusters, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_aws_cluster: gapic_v1.method.wrap_method( - self.delete_aws_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_aws_cluster_agent_token: gapic_v1.method.wrap_method( - self.generate_aws_cluster_agent_token, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_aws_access_token: gapic_v1.method.wrap_method( - self.generate_aws_access_token, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_aws_node_pool: gapic_v1.method.wrap_method( - self.create_aws_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.update_aws_node_pool: gapic_v1.method.wrap_method( - self.update_aws_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.rollback_aws_node_pool_update: gapic_v1.method.wrap_method( - self.rollback_aws_node_pool_update, - default_timeout=60.0, - client_info=client_info, - ), - self.get_aws_node_pool: gapic_v1.method.wrap_method( - self.get_aws_node_pool, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_aws_node_pools: gapic_v1.method.wrap_method( - self.list_aws_node_pools, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_aws_node_pool: gapic_v1.method.wrap_method( - self.delete_aws_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.get_aws_open_id_config: gapic_v1.method.wrap_method( - self.get_aws_open_id_config, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_aws_json_web_keys: gapic_v1.method.wrap_method( - self.get_aws_json_web_keys, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_aws_server_config: gapic_v1.method.wrap_method( - self.get_aws_server_config, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - 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 create_aws_cluster(self) -> Callable[ - [aws_service.CreateAwsClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_aws_cluster(self) -> Callable[ - [aws_service.UpdateAwsClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_aws_cluster(self) -> Callable[ - [aws_service.GetAwsClusterRequest], - Union[ - aws_resources.AwsCluster, - Awaitable[aws_resources.AwsCluster] - ]]: - raise NotImplementedError() - - @property - def list_aws_clusters(self) -> Callable[ - [aws_service.ListAwsClustersRequest], - Union[ - aws_service.ListAwsClustersResponse, - Awaitable[aws_service.ListAwsClustersResponse] - ]]: - raise NotImplementedError() - - @property - def delete_aws_cluster(self) -> Callable[ - [aws_service.DeleteAwsClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def generate_aws_cluster_agent_token(self) -> Callable[ - [aws_service.GenerateAwsClusterAgentTokenRequest], - Union[ - aws_service.GenerateAwsClusterAgentTokenResponse, - Awaitable[aws_service.GenerateAwsClusterAgentTokenResponse] - ]]: - raise NotImplementedError() - - @property - def generate_aws_access_token(self) -> Callable[ - [aws_service.GenerateAwsAccessTokenRequest], - Union[ - aws_service.GenerateAwsAccessTokenResponse, - Awaitable[aws_service.GenerateAwsAccessTokenResponse] - ]]: - raise NotImplementedError() - - @property - def create_aws_node_pool(self) -> Callable[ - [aws_service.CreateAwsNodePoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_aws_node_pool(self) -> Callable[ - [aws_service.UpdateAwsNodePoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def rollback_aws_node_pool_update(self) -> Callable[ - [aws_service.RollbackAwsNodePoolUpdateRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_aws_node_pool(self) -> Callable[ - [aws_service.GetAwsNodePoolRequest], - Union[ - aws_resources.AwsNodePool, - Awaitable[aws_resources.AwsNodePool] - ]]: - raise NotImplementedError() - - @property - def list_aws_node_pools(self) -> Callable[ - [aws_service.ListAwsNodePoolsRequest], - Union[ - aws_service.ListAwsNodePoolsResponse, - Awaitable[aws_service.ListAwsNodePoolsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_aws_node_pool(self) -> Callable[ - [aws_service.DeleteAwsNodePoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_aws_open_id_config(self) -> Callable[ - [aws_service.GetAwsOpenIdConfigRequest], - Union[ - aws_resources.AwsOpenIdConfig, - Awaitable[aws_resources.AwsOpenIdConfig] - ]]: - raise NotImplementedError() - - @property - def get_aws_json_web_keys(self) -> Callable[ - [aws_service.GetAwsJsonWebKeysRequest], - Union[ - aws_resources.AwsJsonWebKeys, - Awaitable[aws_resources.AwsJsonWebKeys] - ]]: - raise NotImplementedError() - - @property - def get_aws_server_config(self) -> Callable[ - [aws_service.GetAwsServerConfigRequest], - Union[ - aws_resources.AwsServerConfig, - Awaitable[aws_resources.AwsServerConfig] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AwsClustersTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc.py deleted file mode 100644 index f21051643280..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc.py +++ /dev/null @@ -1,881 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -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 -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.cloud.gke_multicloud_v1.types import aws_resources -from google.cloud.gke_multicloud_v1.types import aws_service -from google.longrunning import operations_pb2 # type: ignore -from .base import AwsClustersTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": client_call_details.method, - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AwsClustersGrpcTransport(AwsClustersTransport): - """gRPC backend transport for AwsClusters. - - The AwsClusters API provides a single centrally managed - service to create and manage Anthos clusters that run on AWS - infrastructure. - - 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 = 'gkemulticloud.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'gkemulticloud.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._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_aws_cluster(self) -> Callable[ - [aws_service.CreateAwsClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the create aws cluster method over gRPC. - - Creates a new - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource - on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAwsClusterRequest], - ~.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_aws_cluster' not in self._stubs: - self._stubs['create_aws_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsCluster', - request_serializer=aws_service.CreateAwsClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_aws_cluster'] - - @property - def update_aws_cluster(self) -> Callable[ - [aws_service.UpdateAwsClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the update aws cluster method over gRPC. - - Updates an - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - Returns: - Callable[[~.UpdateAwsClusterRequest], - ~.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_aws_cluster' not in self._stubs: - self._stubs['update_aws_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/UpdateAwsCluster', - request_serializer=aws_service.UpdateAwsClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_aws_cluster'] - - @property - def get_aws_cluster(self) -> Callable[ - [aws_service.GetAwsClusterRequest], - aws_resources.AwsCluster]: - r"""Return a callable for the get aws cluster method over gRPC. - - Describes a specific - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. - - Returns: - Callable[[~.GetAwsClusterRequest], - ~.AwsCluster]: - 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_aws_cluster' not in self._stubs: - self._stubs['get_aws_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsCluster', - request_serializer=aws_service.GetAwsClusterRequest.serialize, - response_deserializer=aws_resources.AwsCluster.deserialize, - ) - return self._stubs['get_aws_cluster'] - - @property - def list_aws_clusters(self) -> Callable[ - [aws_service.ListAwsClustersRequest], - aws_service.ListAwsClustersResponse]: - r"""Return a callable for the list aws clusters method over gRPC. - - Lists all [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resources on a given Google Cloud project and region. - - Returns: - Callable[[~.ListAwsClustersRequest], - ~.ListAwsClustersResponse]: - 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_aws_clusters' not in self._stubs: - self._stubs['list_aws_clusters'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/ListAwsClusters', - request_serializer=aws_service.ListAwsClustersRequest.serialize, - response_deserializer=aws_service.ListAwsClustersResponse.deserialize, - ) - return self._stubs['list_aws_clusters'] - - @property - def delete_aws_cluster(self) -> Callable[ - [aws_service.DeleteAwsClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete aws cluster method over gRPC. - - Deletes a specific - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. - - Fails if the cluster has one or more associated - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAwsClusterRequest], - ~.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_aws_cluster' not in self._stubs: - self._stubs['delete_aws_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/DeleteAwsCluster', - request_serializer=aws_service.DeleteAwsClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_aws_cluster'] - - @property - def generate_aws_cluster_agent_token(self) -> Callable[ - [aws_service.GenerateAwsClusterAgentTokenRequest], - aws_service.GenerateAwsClusterAgentTokenResponse]: - r"""Return a callable for the generate aws cluster agent - token method over gRPC. - - Generates an access token for a cluster agent. - - Returns: - Callable[[~.GenerateAwsClusterAgentTokenRequest], - ~.GenerateAwsClusterAgentTokenResponse]: - 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_aws_cluster_agent_token' not in self._stubs: - self._stubs['generate_aws_cluster_agent_token'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GenerateAwsClusterAgentToken', - request_serializer=aws_service.GenerateAwsClusterAgentTokenRequest.serialize, - response_deserializer=aws_service.GenerateAwsClusterAgentTokenResponse.deserialize, - ) - return self._stubs['generate_aws_cluster_agent_token'] - - @property - def generate_aws_access_token(self) -> Callable[ - [aws_service.GenerateAwsAccessTokenRequest], - aws_service.GenerateAwsAccessTokenResponse]: - r"""Return a callable for the generate aws access token method over gRPC. - - Generates a short-lived access token to authenticate to a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. - - Returns: - Callable[[~.GenerateAwsAccessTokenRequest], - ~.GenerateAwsAccessTokenResponse]: - 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_aws_access_token' not in self._stubs: - self._stubs['generate_aws_access_token'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GenerateAwsAccessToken', - request_serializer=aws_service.GenerateAwsAccessTokenRequest.serialize, - response_deserializer=aws_service.GenerateAwsAccessTokenResponse.deserialize, - ) - return self._stubs['generate_aws_access_token'] - - @property - def create_aws_node_pool(self) -> Callable[ - [aws_service.CreateAwsNodePoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the create aws node pool method over gRPC. - - Creates a new - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool], - attached to a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAwsNodePoolRequest], - ~.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_aws_node_pool' not in self._stubs: - self._stubs['create_aws_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsNodePool', - request_serializer=aws_service.CreateAwsNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_aws_node_pool'] - - @property - def update_aws_node_pool(self) -> Callable[ - [aws_service.UpdateAwsNodePoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the update aws node pool method over gRPC. - - Updates an - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. - - Returns: - Callable[[~.UpdateAwsNodePoolRequest], - ~.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_aws_node_pool' not in self._stubs: - self._stubs['update_aws_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/UpdateAwsNodePool', - request_serializer=aws_service.UpdateAwsNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_aws_node_pool'] - - @property - def rollback_aws_node_pool_update(self) -> Callable[ - [aws_service.RollbackAwsNodePoolUpdateRequest], - operations_pb2.Operation]: - r"""Return a callable for the rollback aws node pool update method over gRPC. - - Rolls back a previously aborted or failed - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] update - request. Makes no changes if the last update request - successfully finished. If an update request is in progress, you - cannot rollback the update. You must first cancel or let it - finish unsuccessfully before you can rollback. - - Returns: - Callable[[~.RollbackAwsNodePoolUpdateRequest], - ~.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 'rollback_aws_node_pool_update' not in self._stubs: - self._stubs['rollback_aws_node_pool_update'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/RollbackAwsNodePoolUpdate', - request_serializer=aws_service.RollbackAwsNodePoolUpdateRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rollback_aws_node_pool_update'] - - @property - def get_aws_node_pool(self) -> Callable[ - [aws_service.GetAwsNodePoolRequest], - aws_resources.AwsNodePool]: - r"""Return a callable for the get aws node pool method over gRPC. - - Describes a specific - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource. - - Returns: - Callable[[~.GetAwsNodePoolRequest], - ~.AwsNodePool]: - 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_aws_node_pool' not in self._stubs: - self._stubs['get_aws_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsNodePool', - request_serializer=aws_service.GetAwsNodePoolRequest.serialize, - response_deserializer=aws_resources.AwsNodePool.deserialize, - ) - return self._stubs['get_aws_node_pool'] - - @property - def list_aws_node_pools(self) -> Callable[ - [aws_service.ListAwsNodePoolsRequest], - aws_service.ListAwsNodePoolsResponse]: - r"""Return a callable for the list aws node pools method over gRPC. - - Lists all - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources on a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - Returns: - Callable[[~.ListAwsNodePoolsRequest], - ~.ListAwsNodePoolsResponse]: - 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_aws_node_pools' not in self._stubs: - self._stubs['list_aws_node_pools'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/ListAwsNodePools', - request_serializer=aws_service.ListAwsNodePoolsRequest.serialize, - response_deserializer=aws_service.ListAwsNodePoolsResponse.deserialize, - ) - return self._stubs['list_aws_node_pools'] - - @property - def delete_aws_node_pool(self) -> Callable[ - [aws_service.DeleteAwsNodePoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete aws node pool method over gRPC. - - Deletes a specific - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAwsNodePoolRequest], - ~.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_aws_node_pool' not in self._stubs: - self._stubs['delete_aws_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/DeleteAwsNodePool', - request_serializer=aws_service.DeleteAwsNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_aws_node_pool'] - - @property - def get_aws_open_id_config(self) -> Callable[ - [aws_service.GetAwsOpenIdConfigRequest], - aws_resources.AwsOpenIdConfig]: - r"""Return a callable for the get aws open id config method over gRPC. - - Gets the OIDC discovery document for the cluster. See the - `OpenID Connect Discovery 1.0 - specification `__ - for details. - - Returns: - Callable[[~.GetAwsOpenIdConfigRequest], - ~.AwsOpenIdConfig]: - 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_aws_open_id_config' not in self._stubs: - self._stubs['get_aws_open_id_config'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsOpenIdConfig', - request_serializer=aws_service.GetAwsOpenIdConfigRequest.serialize, - response_deserializer=aws_resources.AwsOpenIdConfig.deserialize, - ) - return self._stubs['get_aws_open_id_config'] - - @property - def get_aws_json_web_keys(self) -> Callable[ - [aws_service.GetAwsJsonWebKeysRequest], - aws_resources.AwsJsonWebKeys]: - r"""Return a callable for the get aws json web keys method over gRPC. - - Gets the public component of the cluster signing keys - in JSON Web Key format. - - Returns: - Callable[[~.GetAwsJsonWebKeysRequest], - ~.AwsJsonWebKeys]: - 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_aws_json_web_keys' not in self._stubs: - self._stubs['get_aws_json_web_keys'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsJsonWebKeys', - request_serializer=aws_service.GetAwsJsonWebKeysRequest.serialize, - response_deserializer=aws_resources.AwsJsonWebKeys.deserialize, - ) - return self._stubs['get_aws_json_web_keys'] - - @property - def get_aws_server_config(self) -> Callable[ - [aws_service.GetAwsServerConfigRequest], - aws_resources.AwsServerConfig]: - r"""Return a callable for the get aws server config method over gRPC. - - Returns information, such as supported AWS regions - and Kubernetes versions, on a given Google Cloud - location. - - Returns: - Callable[[~.GetAwsServerConfigRequest], - ~.AwsServerConfig]: - 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_aws_server_config' not in self._stubs: - self._stubs['get_aws_server_config'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsServerConfig', - request_serializer=aws_service.GetAwsServerConfigRequest.serialize, - response_deserializer=aws_resources.AwsServerConfig.deserialize, - ) - return self._stubs['get_aws_server_config'] - - def close(self): - self._logged_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._logged_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._logged_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._logged_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._logged_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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AwsClustersGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc_asyncio.py deleted file mode 100644 index 16709655e9e5..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/grpc_asyncio.py +++ /dev/null @@ -1,1077 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -import logging as std_logging -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.gke_multicloud_v1.types import aws_resources -from google.cloud.gke_multicloud_v1.types import aws_service -from google.longrunning import operations_pb2 # type: ignore -from .base import AwsClustersTransport, DEFAULT_CLIENT_INFO -from .grpc import AwsClustersGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AwsClustersGrpcAsyncIOTransport(AwsClustersTransport): - """gRPC AsyncIO backend transport for AwsClusters. - - The AwsClusters API provides a single centrally managed - service to create and manage Anthos clusters that run on AWS - infrastructure. - - 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 = 'gkemulticloud.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'gkemulticloud.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_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._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_aws_cluster(self) -> Callable[ - [aws_service.CreateAwsClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create aws cluster method over gRPC. - - Creates a new - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource - on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAwsClusterRequest], - 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_aws_cluster' not in self._stubs: - self._stubs['create_aws_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsCluster', - request_serializer=aws_service.CreateAwsClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_aws_cluster'] - - @property - def update_aws_cluster(self) -> Callable[ - [aws_service.UpdateAwsClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update aws cluster method over gRPC. - - Updates an - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - Returns: - Callable[[~.UpdateAwsClusterRequest], - 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_aws_cluster' not in self._stubs: - self._stubs['update_aws_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/UpdateAwsCluster', - request_serializer=aws_service.UpdateAwsClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_aws_cluster'] - - @property - def get_aws_cluster(self) -> Callable[ - [aws_service.GetAwsClusterRequest], - Awaitable[aws_resources.AwsCluster]]: - r"""Return a callable for the get aws cluster method over gRPC. - - Describes a specific - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. - - Returns: - Callable[[~.GetAwsClusterRequest], - Awaitable[~.AwsCluster]]: - 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_aws_cluster' not in self._stubs: - self._stubs['get_aws_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsCluster', - request_serializer=aws_service.GetAwsClusterRequest.serialize, - response_deserializer=aws_resources.AwsCluster.deserialize, - ) - return self._stubs['get_aws_cluster'] - - @property - def list_aws_clusters(self) -> Callable[ - [aws_service.ListAwsClustersRequest], - Awaitable[aws_service.ListAwsClustersResponse]]: - r"""Return a callable for the list aws clusters method over gRPC. - - Lists all [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resources on a given Google Cloud project and region. - - Returns: - Callable[[~.ListAwsClustersRequest], - Awaitable[~.ListAwsClustersResponse]]: - 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_aws_clusters' not in self._stubs: - self._stubs['list_aws_clusters'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/ListAwsClusters', - request_serializer=aws_service.ListAwsClustersRequest.serialize, - response_deserializer=aws_service.ListAwsClustersResponse.deserialize, - ) - return self._stubs['list_aws_clusters'] - - @property - def delete_aws_cluster(self) -> Callable[ - [aws_service.DeleteAwsClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete aws cluster method over gRPC. - - Deletes a specific - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. - - Fails if the cluster has one or more associated - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAwsClusterRequest], - 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_aws_cluster' not in self._stubs: - self._stubs['delete_aws_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/DeleteAwsCluster', - request_serializer=aws_service.DeleteAwsClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_aws_cluster'] - - @property - def generate_aws_cluster_agent_token(self) -> Callable[ - [aws_service.GenerateAwsClusterAgentTokenRequest], - Awaitable[aws_service.GenerateAwsClusterAgentTokenResponse]]: - r"""Return a callable for the generate aws cluster agent - token method over gRPC. - - Generates an access token for a cluster agent. - - Returns: - Callable[[~.GenerateAwsClusterAgentTokenRequest], - Awaitable[~.GenerateAwsClusterAgentTokenResponse]]: - 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_aws_cluster_agent_token' not in self._stubs: - self._stubs['generate_aws_cluster_agent_token'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GenerateAwsClusterAgentToken', - request_serializer=aws_service.GenerateAwsClusterAgentTokenRequest.serialize, - response_deserializer=aws_service.GenerateAwsClusterAgentTokenResponse.deserialize, - ) - return self._stubs['generate_aws_cluster_agent_token'] - - @property - def generate_aws_access_token(self) -> Callable[ - [aws_service.GenerateAwsAccessTokenRequest], - Awaitable[aws_service.GenerateAwsAccessTokenResponse]]: - r"""Return a callable for the generate aws access token method over gRPC. - - Generates a short-lived access token to authenticate to a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. - - Returns: - Callable[[~.GenerateAwsAccessTokenRequest], - Awaitable[~.GenerateAwsAccessTokenResponse]]: - 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_aws_access_token' not in self._stubs: - self._stubs['generate_aws_access_token'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GenerateAwsAccessToken', - request_serializer=aws_service.GenerateAwsAccessTokenRequest.serialize, - response_deserializer=aws_service.GenerateAwsAccessTokenResponse.deserialize, - ) - return self._stubs['generate_aws_access_token'] - - @property - def create_aws_node_pool(self) -> Callable[ - [aws_service.CreateAwsNodePoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create aws node pool method over gRPC. - - Creates a new - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool], - attached to a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAwsNodePoolRequest], - 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_aws_node_pool' not in self._stubs: - self._stubs['create_aws_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsNodePool', - request_serializer=aws_service.CreateAwsNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_aws_node_pool'] - - @property - def update_aws_node_pool(self) -> Callable[ - [aws_service.UpdateAwsNodePoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update aws node pool method over gRPC. - - Updates an - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. - - Returns: - Callable[[~.UpdateAwsNodePoolRequest], - 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_aws_node_pool' not in self._stubs: - self._stubs['update_aws_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/UpdateAwsNodePool', - request_serializer=aws_service.UpdateAwsNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_aws_node_pool'] - - @property - def rollback_aws_node_pool_update(self) -> Callable[ - [aws_service.RollbackAwsNodePoolUpdateRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the rollback aws node pool update method over gRPC. - - Rolls back a previously aborted or failed - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] update - request. Makes no changes if the last update request - successfully finished. If an update request is in progress, you - cannot rollback the update. You must first cancel or let it - finish unsuccessfully before you can rollback. - - Returns: - Callable[[~.RollbackAwsNodePoolUpdateRequest], - 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 'rollback_aws_node_pool_update' not in self._stubs: - self._stubs['rollback_aws_node_pool_update'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/RollbackAwsNodePoolUpdate', - request_serializer=aws_service.RollbackAwsNodePoolUpdateRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['rollback_aws_node_pool_update'] - - @property - def get_aws_node_pool(self) -> Callable[ - [aws_service.GetAwsNodePoolRequest], - Awaitable[aws_resources.AwsNodePool]]: - r"""Return a callable for the get aws node pool method over gRPC. - - Describes a specific - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource. - - Returns: - Callable[[~.GetAwsNodePoolRequest], - Awaitable[~.AwsNodePool]]: - 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_aws_node_pool' not in self._stubs: - self._stubs['get_aws_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsNodePool', - request_serializer=aws_service.GetAwsNodePoolRequest.serialize, - response_deserializer=aws_resources.AwsNodePool.deserialize, - ) - return self._stubs['get_aws_node_pool'] - - @property - def list_aws_node_pools(self) -> Callable[ - [aws_service.ListAwsNodePoolsRequest], - Awaitable[aws_service.ListAwsNodePoolsResponse]]: - r"""Return a callable for the list aws node pools method over gRPC. - - Lists all - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources on a given - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - Returns: - Callable[[~.ListAwsNodePoolsRequest], - Awaitable[~.ListAwsNodePoolsResponse]]: - 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_aws_node_pools' not in self._stubs: - self._stubs['list_aws_node_pools'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/ListAwsNodePools', - request_serializer=aws_service.ListAwsNodePoolsRequest.serialize, - response_deserializer=aws_service.ListAwsNodePoolsResponse.deserialize, - ) - return self._stubs['list_aws_node_pools'] - - @property - def delete_aws_node_pool(self) -> Callable[ - [aws_service.DeleteAwsNodePoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete aws node pool method over gRPC. - - Deletes a specific - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAwsNodePoolRequest], - 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_aws_node_pool' not in self._stubs: - self._stubs['delete_aws_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/DeleteAwsNodePool', - request_serializer=aws_service.DeleteAwsNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_aws_node_pool'] - - @property - def get_aws_open_id_config(self) -> Callable[ - [aws_service.GetAwsOpenIdConfigRequest], - Awaitable[aws_resources.AwsOpenIdConfig]]: - r"""Return a callable for the get aws open id config method over gRPC. - - Gets the OIDC discovery document for the cluster. See the - `OpenID Connect Discovery 1.0 - specification `__ - for details. - - Returns: - Callable[[~.GetAwsOpenIdConfigRequest], - Awaitable[~.AwsOpenIdConfig]]: - 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_aws_open_id_config' not in self._stubs: - self._stubs['get_aws_open_id_config'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsOpenIdConfig', - request_serializer=aws_service.GetAwsOpenIdConfigRequest.serialize, - response_deserializer=aws_resources.AwsOpenIdConfig.deserialize, - ) - return self._stubs['get_aws_open_id_config'] - - @property - def get_aws_json_web_keys(self) -> Callable[ - [aws_service.GetAwsJsonWebKeysRequest], - Awaitable[aws_resources.AwsJsonWebKeys]]: - r"""Return a callable for the get aws json web keys method over gRPC. - - Gets the public component of the cluster signing keys - in JSON Web Key format. - - Returns: - Callable[[~.GetAwsJsonWebKeysRequest], - Awaitable[~.AwsJsonWebKeys]]: - 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_aws_json_web_keys' not in self._stubs: - self._stubs['get_aws_json_web_keys'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsJsonWebKeys', - request_serializer=aws_service.GetAwsJsonWebKeysRequest.serialize, - response_deserializer=aws_resources.AwsJsonWebKeys.deserialize, - ) - return self._stubs['get_aws_json_web_keys'] - - @property - def get_aws_server_config(self) -> Callable[ - [aws_service.GetAwsServerConfigRequest], - Awaitable[aws_resources.AwsServerConfig]]: - r"""Return a callable for the get aws server config method over gRPC. - - Returns information, such as supported AWS regions - and Kubernetes versions, on a given Google Cloud - location. - - Returns: - Callable[[~.GetAwsServerConfigRequest], - Awaitable[~.AwsServerConfig]]: - 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_aws_server_config' not in self._stubs: - self._stubs['get_aws_server_config'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsServerConfig', - request_serializer=aws_service.GetAwsServerConfigRequest.serialize, - response_deserializer=aws_resources.AwsServerConfig.deserialize, - ) - return self._stubs['get_aws_server_config'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.create_aws_cluster: self._wrap_method( - self.create_aws_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_aws_cluster: self._wrap_method( - self.update_aws_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_aws_cluster: self._wrap_method( - self.get_aws_cluster, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_aws_clusters: self._wrap_method( - self.list_aws_clusters, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_aws_cluster: self._wrap_method( - self.delete_aws_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_aws_cluster_agent_token: self._wrap_method( - self.generate_aws_cluster_agent_token, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_aws_access_token: self._wrap_method( - self.generate_aws_access_token, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_aws_node_pool: self._wrap_method( - self.create_aws_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.update_aws_node_pool: self._wrap_method( - self.update_aws_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.rollback_aws_node_pool_update: self._wrap_method( - self.rollback_aws_node_pool_update, - default_timeout=60.0, - client_info=client_info, - ), - self.get_aws_node_pool: self._wrap_method( - self.get_aws_node_pool, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_aws_node_pools: self._wrap_method( - self.list_aws_node_pools, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_aws_node_pool: self._wrap_method( - self.delete_aws_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.get_aws_open_id_config: self._wrap_method( - self.get_aws_open_id_config, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_aws_json_web_keys: self._wrap_method( - self.get_aws_json_web_keys, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_aws_server_config: self._wrap_method( - self.get_aws_server_config, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @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._logged_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._logged_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._logged_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._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'AwsClustersGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest.py deleted file mode 100644 index 8078628a030f..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest.py +++ /dev/null @@ -1,3204 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # 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 gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.gke_multicloud_v1.types import aws_resources -from google.cloud.gke_multicloud_v1.types import aws_service -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseAwsClustersRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class AwsClustersRestInterceptor: - """Interceptor for AwsClusters. - - 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 AwsClustersRestTransport. - - .. code-block:: python - class MyCustomAwsClustersInterceptor(AwsClustersRestInterceptor): - def pre_create_aws_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_aws_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_aws_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_aws_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_aws_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_aws_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_aws_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_aws_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_aws_access_token(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_aws_access_token(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_aws_cluster_agent_token(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_aws_cluster_agent_token(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_aws_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_aws_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_aws_json_web_keys(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_aws_json_web_keys(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_aws_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_aws_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_aws_open_id_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_aws_open_id_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_aws_server_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_aws_server_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_aws_clusters(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_aws_clusters(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_aws_node_pools(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_aws_node_pools(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_rollback_aws_node_pool_update(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_rollback_aws_node_pool_update(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_aws_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_aws_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_aws_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_aws_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AwsClustersRestTransport(interceptor=MyCustomAwsClustersInterceptor()) - client = AwsClustersClient(transport=transport) - - - """ - def pre_create_aws_cluster(self, request: aws_service.CreateAwsClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.CreateAwsClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_aws_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_create_aws_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_aws_cluster - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_create_aws_node_pool(self, request: aws_service.CreateAwsNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.CreateAwsNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_aws_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_create_aws_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_aws_node_pool - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_delete_aws_cluster(self, request: aws_service.DeleteAwsClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.DeleteAwsClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_aws_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_delete_aws_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_aws_cluster - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_delete_aws_node_pool(self, request: aws_service.DeleteAwsNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.DeleteAwsNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_aws_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_delete_aws_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_aws_node_pool - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_generate_aws_access_token(self, request: aws_service.GenerateAwsAccessTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GenerateAwsAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for generate_aws_access_token - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_generate_aws_access_token(self, response: aws_service.GenerateAwsAccessTokenResponse) -> aws_service.GenerateAwsAccessTokenResponse: - """Post-rpc interceptor for generate_aws_access_token - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_generate_aws_cluster_agent_token(self, request: aws_service.GenerateAwsClusterAgentTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GenerateAwsClusterAgentTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for generate_aws_cluster_agent_token - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_generate_aws_cluster_agent_token(self, response: aws_service.GenerateAwsClusterAgentTokenResponse) -> aws_service.GenerateAwsClusterAgentTokenResponse: - """Post-rpc interceptor for generate_aws_cluster_agent_token - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_get_aws_cluster(self, request: aws_service.GetAwsClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GetAwsClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_aws_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_get_aws_cluster(self, response: aws_resources.AwsCluster) -> aws_resources.AwsCluster: - """Post-rpc interceptor for get_aws_cluster - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_get_aws_json_web_keys(self, request: aws_service.GetAwsJsonWebKeysRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GetAwsJsonWebKeysRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_aws_json_web_keys - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_get_aws_json_web_keys(self, response: aws_resources.AwsJsonWebKeys) -> aws_resources.AwsJsonWebKeys: - """Post-rpc interceptor for get_aws_json_web_keys - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_get_aws_node_pool(self, request: aws_service.GetAwsNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GetAwsNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_aws_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_get_aws_node_pool(self, response: aws_resources.AwsNodePool) -> aws_resources.AwsNodePool: - """Post-rpc interceptor for get_aws_node_pool - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_get_aws_open_id_config(self, request: aws_service.GetAwsOpenIdConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GetAwsOpenIdConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_aws_open_id_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_get_aws_open_id_config(self, response: aws_resources.AwsOpenIdConfig) -> aws_resources.AwsOpenIdConfig: - """Post-rpc interceptor for get_aws_open_id_config - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_get_aws_server_config(self, request: aws_service.GetAwsServerConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.GetAwsServerConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_aws_server_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_get_aws_server_config(self, response: aws_resources.AwsServerConfig) -> aws_resources.AwsServerConfig: - """Post-rpc interceptor for get_aws_server_config - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_list_aws_clusters(self, request: aws_service.ListAwsClustersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.ListAwsClustersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_aws_clusters - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_list_aws_clusters(self, response: aws_service.ListAwsClustersResponse) -> aws_service.ListAwsClustersResponse: - """Post-rpc interceptor for list_aws_clusters - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_list_aws_node_pools(self, request: aws_service.ListAwsNodePoolsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.ListAwsNodePoolsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_aws_node_pools - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_list_aws_node_pools(self, response: aws_service.ListAwsNodePoolsResponse) -> aws_service.ListAwsNodePoolsResponse: - """Post-rpc interceptor for list_aws_node_pools - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_rollback_aws_node_pool_update(self, request: aws_service.RollbackAwsNodePoolUpdateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.RollbackAwsNodePoolUpdateRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for rollback_aws_node_pool_update - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_rollback_aws_node_pool_update(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for rollback_aws_node_pool_update - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_update_aws_cluster(self, request: aws_service.UpdateAwsClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.UpdateAwsClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_aws_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_update_aws_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_aws_cluster - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_update_aws_node_pool(self, request: aws_service.UpdateAwsNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[aws_service.UpdateAwsNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_aws_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters server. - """ - return request, metadata - - def post_update_aws_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_aws_node_pool - - Override in a subclass to manipulate the response - after it is returned by the AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters 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 AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters 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 AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters 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 AwsClusters server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the AwsClusters 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 AwsClusters server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AwsClustersRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AwsClustersRestInterceptor - - -class AwsClustersRestTransport(_BaseAwsClustersRestTransport): - """REST backend synchronous transport for AwsClusters. - - The AwsClusters API provides a single centrally managed - service to create and manage Anthos clusters that run on AWS - infrastructure. - - 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 = 'gkemulticloud.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[AwsClustersRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - 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 AwsClustersRestInterceptor() - 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 _CreateAwsCluster(_BaseAwsClustersRestTransport._BaseCreateAwsCluster, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.CreateAwsCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: aws_service.CreateAwsClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create aws cluster method over HTTP. - - Args: - request (~.aws_service.CreateAwsClusterRequest): - The request object. Request message for ``AwsClusters.CreateAwsCluster`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseCreateAwsCluster._get_http_options() - - request, metadata = self._interceptor.pre_create_aws_cluster(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseCreateAwsCluster._get_transcoded_request(http_options, request) - - body = _BaseAwsClustersRestTransport._BaseCreateAwsCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseCreateAwsCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.CreateAwsCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "CreateAwsCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._CreateAwsCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_aws_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.create_aws_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "CreateAwsCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateAwsNodePool(_BaseAwsClustersRestTransport._BaseCreateAwsNodePool, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.CreateAwsNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: aws_service.CreateAwsNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create aws node pool method over HTTP. - - Args: - request (~.aws_service.CreateAwsNodePoolRequest): - The request object. Response message for ``AwsClusters.CreateAwsNodePool`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseCreateAwsNodePool._get_http_options() - - request, metadata = self._interceptor.pre_create_aws_node_pool(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseCreateAwsNodePool._get_transcoded_request(http_options, request) - - body = _BaseAwsClustersRestTransport._BaseCreateAwsNodePool._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseCreateAwsNodePool._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.CreateAwsNodePool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "CreateAwsNodePool", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._CreateAwsNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_aws_node_pool(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.create_aws_node_pool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "CreateAwsNodePool", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteAwsCluster(_BaseAwsClustersRestTransport._BaseDeleteAwsCluster, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.DeleteAwsCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: aws_service.DeleteAwsClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete aws cluster method over HTTP. - - Args: - request (~.aws_service.DeleteAwsClusterRequest): - The request object. Request message for ``AwsClusters.DeleteAwsCluster`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseDeleteAwsCluster._get_http_options() - - request, metadata = self._interceptor.pre_delete_aws_cluster(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseDeleteAwsCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseDeleteAwsCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.DeleteAwsCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "DeleteAwsCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._DeleteAwsCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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_aws_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.delete_aws_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "DeleteAwsCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteAwsNodePool(_BaseAwsClustersRestTransport._BaseDeleteAwsNodePool, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.DeleteAwsNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: aws_service.DeleteAwsNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete aws node pool method over HTTP. - - Args: - request (~.aws_service.DeleteAwsNodePoolRequest): - The request object. Request message for ``AwsClusters.DeleteAwsNodePool`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseDeleteAwsNodePool._get_http_options() - - request, metadata = self._interceptor.pre_delete_aws_node_pool(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseDeleteAwsNodePool._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseDeleteAwsNodePool._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.DeleteAwsNodePool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "DeleteAwsNodePool", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._DeleteAwsNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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_aws_node_pool(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.delete_aws_node_pool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "DeleteAwsNodePool", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GenerateAwsAccessToken(_BaseAwsClustersRestTransport._BaseGenerateAwsAccessToken, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.GenerateAwsAccessToken") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: aws_service.GenerateAwsAccessTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> aws_service.GenerateAwsAccessTokenResponse: - r"""Call the generate aws access token method over HTTP. - - Args: - request (~.aws_service.GenerateAwsAccessTokenRequest): - The request object. Request message for - ``AwsClusters.GenerateAwsAccessToken`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.aws_service.GenerateAwsAccessTokenResponse: - Response message for - ``AwsClusters.GenerateAwsAccessToken`` method. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseGenerateAwsAccessToken._get_http_options() - - request, metadata = self._interceptor.pre_generate_aws_access_token(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseGenerateAwsAccessToken._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseGenerateAwsAccessToken._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GenerateAwsAccessToken", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GenerateAwsAccessToken", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._GenerateAwsAccessToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = aws_service.GenerateAwsAccessTokenResponse() - pb_resp = aws_service.GenerateAwsAccessTokenResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_generate_aws_access_token(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = aws_service.GenerateAwsAccessTokenResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.generate_aws_access_token", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GenerateAwsAccessToken", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GenerateAwsClusterAgentToken(_BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.GenerateAwsClusterAgentToken") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: aws_service.GenerateAwsClusterAgentTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> aws_service.GenerateAwsClusterAgentTokenResponse: - r"""Call the generate aws cluster - agent token method over HTTP. - - Args: - request (~.aws_service.GenerateAwsClusterAgentTokenRequest): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.aws_service.GenerateAwsClusterAgentTokenResponse: - - """ - - http_options = _BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken._get_http_options() - - request, metadata = self._interceptor.pre_generate_aws_cluster_agent_token(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken._get_transcoded_request(http_options, request) - - body = _BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GenerateAwsClusterAgentToken", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GenerateAwsClusterAgentToken", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._GenerateAwsClusterAgentToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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 = aws_service.GenerateAwsClusterAgentTokenResponse() - pb_resp = aws_service.GenerateAwsClusterAgentTokenResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_generate_aws_cluster_agent_token(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = aws_service.GenerateAwsClusterAgentTokenResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.generate_aws_cluster_agent_token", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GenerateAwsClusterAgentToken", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAwsCluster(_BaseAwsClustersRestTransport._BaseGetAwsCluster, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.GetAwsCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: aws_service.GetAwsClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> aws_resources.AwsCluster: - r"""Call the get aws cluster method over HTTP. - - Args: - request (~.aws_service.GetAwsClusterRequest): - The request object. Request message for ``AwsClusters.GetAwsCluster`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.aws_resources.AwsCluster: - An Anthos cluster running on AWS. - """ - - http_options = _BaseAwsClustersRestTransport._BaseGetAwsCluster._get_http_options() - - request, metadata = self._interceptor.pre_get_aws_cluster(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseGetAwsCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseGetAwsCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetAwsCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetAwsCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._GetAwsCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = aws_resources.AwsCluster() - pb_resp = aws_resources.AwsCluster.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_aws_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = aws_resources.AwsCluster.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.get_aws_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetAwsCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAwsJsonWebKeys(_BaseAwsClustersRestTransport._BaseGetAwsJsonWebKeys, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.GetAwsJsonWebKeys") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: aws_service.GetAwsJsonWebKeysRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> aws_resources.AwsJsonWebKeys: - r"""Call the get aws json web keys method over HTTP. - - Args: - request (~.aws_service.GetAwsJsonWebKeysRequest): - The request object. GetAwsJsonWebKeysRequest gets the public component of - the keys used by the cluster to sign token requests. - This will be the jwks_uri for the discover document - returned by getOpenIDConfig. See the OpenID Connect - Discovery 1.0 specification for details. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.aws_resources.AwsJsonWebKeys: - AwsJsonWebKeys is a valid JSON Web - Key Set as specififed in RFC 7517. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseGetAwsJsonWebKeys._get_http_options() - - request, metadata = self._interceptor.pre_get_aws_json_web_keys(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseGetAwsJsonWebKeys._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseGetAwsJsonWebKeys._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetAwsJsonWebKeys", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetAwsJsonWebKeys", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._GetAwsJsonWebKeys._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = aws_resources.AwsJsonWebKeys() - pb_resp = aws_resources.AwsJsonWebKeys.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_aws_json_web_keys(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = aws_resources.AwsJsonWebKeys.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.get_aws_json_web_keys", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetAwsJsonWebKeys", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAwsNodePool(_BaseAwsClustersRestTransport._BaseGetAwsNodePool, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.GetAwsNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: aws_service.GetAwsNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> aws_resources.AwsNodePool: - r"""Call the get aws node pool method over HTTP. - - Args: - request (~.aws_service.GetAwsNodePoolRequest): - The request object. Request message for ``AwsClusters.GetAwsNodePool`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.aws_resources.AwsNodePool: - An Anthos node pool running on AWS. - """ - - http_options = _BaseAwsClustersRestTransport._BaseGetAwsNodePool._get_http_options() - - request, metadata = self._interceptor.pre_get_aws_node_pool(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseGetAwsNodePool._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseGetAwsNodePool._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetAwsNodePool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetAwsNodePool", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._GetAwsNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = aws_resources.AwsNodePool() - pb_resp = aws_resources.AwsNodePool.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_aws_node_pool(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = aws_resources.AwsNodePool.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.get_aws_node_pool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetAwsNodePool", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAwsOpenIdConfig(_BaseAwsClustersRestTransport._BaseGetAwsOpenIdConfig, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.GetAwsOpenIdConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: aws_service.GetAwsOpenIdConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> aws_resources.AwsOpenIdConfig: - r"""Call the get aws open id config method over HTTP. - - Args: - request (~.aws_service.GetAwsOpenIdConfigRequest): - The request object. GetAwsOpenIdConfigRequest gets the - OIDC discovery document for the cluster. - See the OpenID Connect Discovery 1.0 - specification for details. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.aws_resources.AwsOpenIdConfig: - AwsOpenIdConfig is an OIDC discovery - document for the cluster. See the OpenID - Connect Discovery 1.0 specification for - details. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseGetAwsOpenIdConfig._get_http_options() - - request, metadata = self._interceptor.pre_get_aws_open_id_config(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseGetAwsOpenIdConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseGetAwsOpenIdConfig._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetAwsOpenIdConfig", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetAwsOpenIdConfig", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._GetAwsOpenIdConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = aws_resources.AwsOpenIdConfig() - pb_resp = aws_resources.AwsOpenIdConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_aws_open_id_config(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = aws_resources.AwsOpenIdConfig.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.get_aws_open_id_config", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetAwsOpenIdConfig", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAwsServerConfig(_BaseAwsClustersRestTransport._BaseGetAwsServerConfig, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.GetAwsServerConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: aws_service.GetAwsServerConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> aws_resources.AwsServerConfig: - r"""Call the get aws server config method over HTTP. - - Args: - request (~.aws_service.GetAwsServerConfigRequest): - The request object. GetAwsServerConfigRequest gets the - server config of GKE cluster on AWS. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.aws_resources.AwsServerConfig: - AwsServerConfig is the configuration - of GKE cluster on AWS. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseGetAwsServerConfig._get_http_options() - - request, metadata = self._interceptor.pre_get_aws_server_config(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseGetAwsServerConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseGetAwsServerConfig._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetAwsServerConfig", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetAwsServerConfig", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._GetAwsServerConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = aws_resources.AwsServerConfig() - pb_resp = aws_resources.AwsServerConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_aws_server_config(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = aws_resources.AwsServerConfig.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.get_aws_server_config", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetAwsServerConfig", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListAwsClusters(_BaseAwsClustersRestTransport._BaseListAwsClusters, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.ListAwsClusters") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: aws_service.ListAwsClustersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> aws_service.ListAwsClustersResponse: - r"""Call the list aws clusters method over HTTP. - - Args: - request (~.aws_service.ListAwsClustersRequest): - The request object. Request message for ``AwsClusters.ListAwsClusters`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.aws_service.ListAwsClustersResponse: - Response message for ``AwsClusters.ListAwsClusters`` - method. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseListAwsClusters._get_http_options() - - request, metadata = self._interceptor.pre_list_aws_clusters(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseListAwsClusters._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseListAwsClusters._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.ListAwsClusters", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "ListAwsClusters", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._ListAwsClusters._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = aws_service.ListAwsClustersResponse() - pb_resp = aws_service.ListAwsClustersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_aws_clusters(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = aws_service.ListAwsClustersResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.list_aws_clusters", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "ListAwsClusters", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListAwsNodePools(_BaseAwsClustersRestTransport._BaseListAwsNodePools, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.ListAwsNodePools") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: aws_service.ListAwsNodePoolsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> aws_service.ListAwsNodePoolsResponse: - r"""Call the list aws node pools method over HTTP. - - Args: - request (~.aws_service.ListAwsNodePoolsRequest): - The request object. Request message for ``AwsClusters.ListAwsNodePools`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.aws_service.ListAwsNodePoolsResponse: - Response message for ``AwsClusters.ListAwsNodePools`` - method. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseListAwsNodePools._get_http_options() - - request, metadata = self._interceptor.pre_list_aws_node_pools(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseListAwsNodePools._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseListAwsNodePools._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.ListAwsNodePools", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "ListAwsNodePools", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._ListAwsNodePools._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = aws_service.ListAwsNodePoolsResponse() - pb_resp = aws_service.ListAwsNodePoolsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_aws_node_pools(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = aws_service.ListAwsNodePoolsResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.list_aws_node_pools", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "ListAwsNodePools", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _RollbackAwsNodePoolUpdate(_BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.RollbackAwsNodePoolUpdate") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: aws_service.RollbackAwsNodePoolUpdateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the rollback aws node pool - update method over HTTP. - - Args: - request (~.aws_service.RollbackAwsNodePoolUpdateRequest): - The request object. Request message for - ``AwsClusters.RollbackAwsNodePoolUpdate`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate._get_http_options() - - request, metadata = self._interceptor.pre_rollback_aws_node_pool_update(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate._get_transcoded_request(http_options, request) - - body = _BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.RollbackAwsNodePoolUpdate", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "RollbackAwsNodePoolUpdate", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._RollbackAwsNodePoolUpdate._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_rollback_aws_node_pool_update(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.rollback_aws_node_pool_update", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "RollbackAwsNodePoolUpdate", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateAwsCluster(_BaseAwsClustersRestTransport._BaseUpdateAwsCluster, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.UpdateAwsCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: aws_service.UpdateAwsClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update aws cluster method over HTTP. - - Args: - request (~.aws_service.UpdateAwsClusterRequest): - The request object. Request message for ``AwsClusters.UpdateAwsCluster`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseUpdateAwsCluster._get_http_options() - - request, metadata = self._interceptor.pre_update_aws_cluster(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseUpdateAwsCluster._get_transcoded_request(http_options, request) - - body = _BaseAwsClustersRestTransport._BaseUpdateAwsCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseUpdateAwsCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.UpdateAwsCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "UpdateAwsCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._UpdateAwsCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_aws_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.update_aws_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "UpdateAwsCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateAwsNodePool(_BaseAwsClustersRestTransport._BaseUpdateAwsNodePool, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.UpdateAwsNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: aws_service.UpdateAwsNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update aws node pool method over HTTP. - - Args: - request (~.aws_service.UpdateAwsNodePoolRequest): - The request object. Request message for ``AwsClusters.UpdateAwsNodePool`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAwsClustersRestTransport._BaseUpdateAwsNodePool._get_http_options() - - request, metadata = self._interceptor.pre_update_aws_node_pool(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseUpdateAwsNodePool._get_transcoded_request(http_options, request) - - body = _BaseAwsClustersRestTransport._BaseUpdateAwsNodePool._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseUpdateAwsNodePool._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.UpdateAwsNodePool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "UpdateAwsNodePool", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._UpdateAwsNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_aws_node_pool(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersClient.update_aws_node_pool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "UpdateAwsNodePool", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_aws_cluster(self) -> Callable[ - [aws_service.CreateAwsClusterRequest], - 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._CreateAwsCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_aws_node_pool(self) -> Callable[ - [aws_service.CreateAwsNodePoolRequest], - 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._CreateAwsNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_aws_cluster(self) -> Callable[ - [aws_service.DeleteAwsClusterRequest], - 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._DeleteAwsCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_aws_node_pool(self) -> Callable[ - [aws_service.DeleteAwsNodePoolRequest], - 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._DeleteAwsNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_aws_access_token(self) -> Callable[ - [aws_service.GenerateAwsAccessTokenRequest], - aws_service.GenerateAwsAccessTokenResponse]: - # 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._GenerateAwsAccessToken(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_aws_cluster_agent_token(self) -> Callable[ - [aws_service.GenerateAwsClusterAgentTokenRequest], - aws_service.GenerateAwsClusterAgentTokenResponse]: - # 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._GenerateAwsClusterAgentToken(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_aws_cluster(self) -> Callable[ - [aws_service.GetAwsClusterRequest], - aws_resources.AwsCluster]: - # 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._GetAwsCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_aws_json_web_keys(self) -> Callable[ - [aws_service.GetAwsJsonWebKeysRequest], - aws_resources.AwsJsonWebKeys]: - # 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._GetAwsJsonWebKeys(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_aws_node_pool(self) -> Callable[ - [aws_service.GetAwsNodePoolRequest], - aws_resources.AwsNodePool]: - # 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._GetAwsNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_aws_open_id_config(self) -> Callable[ - [aws_service.GetAwsOpenIdConfigRequest], - aws_resources.AwsOpenIdConfig]: - # 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._GetAwsOpenIdConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_aws_server_config(self) -> Callable[ - [aws_service.GetAwsServerConfigRequest], - aws_resources.AwsServerConfig]: - # 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._GetAwsServerConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_aws_clusters(self) -> Callable[ - [aws_service.ListAwsClustersRequest], - aws_service.ListAwsClustersResponse]: - # 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._ListAwsClusters(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_aws_node_pools(self) -> Callable[ - [aws_service.ListAwsNodePoolsRequest], - aws_service.ListAwsNodePoolsResponse]: - # 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._ListAwsNodePools(self._session, self._host, self._interceptor) # type: ignore - - @property - def rollback_aws_node_pool_update(self) -> Callable[ - [aws_service.RollbackAwsNodePoolUpdateRequest], - 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._RollbackAwsNodePoolUpdate(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_aws_cluster(self) -> Callable[ - [aws_service.UpdateAwsClusterRequest], - 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._UpdateAwsCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_aws_node_pool(self) -> Callable[ - [aws_service.UpdateAwsNodePoolRequest], - 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._UpdateAwsNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseAwsClustersRestTransport._BaseCancelOperation, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseAwsClustersRestTransport._BaseCancelOperation._get_http_options() - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseAwsClustersRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.CancelOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "CancelOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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(_BaseAwsClustersRestTransport._BaseDeleteOperation, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseAwsClustersRestTransport._BaseDeleteOperation._get_http_options() - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.DeleteOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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(_BaseAwsClustersRestTransport._BaseGetOperation, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseAwsClustersRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.GetOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersAsyncClient.GetOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "GetOperation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseAwsClustersRestTransport._BaseListOperations, AwsClustersRestStub): - def __hash__(self): - return hash("AwsClustersRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseAwsClustersRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseAwsClustersRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAwsClustersRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AwsClustersClient.ListOperations", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AwsClustersRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AwsClustersAsyncClient.ListOperations", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AwsClusters", - "rpcName": "ListOperations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AwsClustersRestTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest_base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest_base.py deleted file mode 100644 index 011515166ec1..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/aws_clusters/transports/rest_base.py +++ /dev/null @@ -1,834 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import AwsClustersTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.gke_multicloud_v1.types import aws_resources -from google.cloud.gke_multicloud_v1.types import aws_service -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseAwsClustersRestTransport(AwsClustersTransport): - """Base REST backend transport for AwsClusters. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - 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 = 'gkemulticloud.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[Any]): 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. - 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 - 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 - ) - - class _BaseCreateAwsCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "awsClusterId" : "", } - - @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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/awsClusters', - 'body': 'aws_cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.CreateAwsClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseCreateAwsCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseCreateAwsNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "awsNodePoolId" : "", } - - @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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/awsClusters/*}/awsNodePools', - 'body': 'aws_node_pool', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.CreateAwsNodePoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseCreateAwsNodePool._get_unset_required_fields(query_params)) - - return query_params - - class _BaseDeleteAwsCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/awsClusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.DeleteAwsClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseDeleteAwsCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseDeleteAwsNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/awsClusters/*/awsNodePools/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.DeleteAwsNodePoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseDeleteAwsNodePool._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGenerateAwsAccessToken: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{aws_cluster=projects/*/locations/*/awsClusters/*}:generateAwsAccessToken', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.GenerateAwsAccessTokenRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseGenerateAwsAccessToken._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGenerateAwsClusterAgentToken: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{aws_cluster=projects/*/locations/*/awsClusters/*}:generateAwsClusterAgentToken', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.GenerateAwsClusterAgentTokenRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseGenerateAwsClusterAgentToken._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAwsCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/awsClusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.GetAwsClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseGetAwsCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAwsJsonWebKeys: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{aws_cluster=projects/*/locations/*/awsClusters/*}/jwks', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.GetAwsJsonWebKeysRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseGetAwsJsonWebKeys._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAwsNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/awsClusters/*/awsNodePools/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.GetAwsNodePoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseGetAwsNodePool._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAwsOpenIdConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{aws_cluster=projects/*/locations/*/awsClusters/*}/.well-known/openid-configuration', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.GetAwsOpenIdConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseGetAwsOpenIdConfig._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAwsServerConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/awsServerConfig}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.GetAwsServerConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseGetAwsServerConfig._get_unset_required_fields(query_params)) - - return query_params - - class _BaseListAwsClusters: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/awsClusters', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.ListAwsClustersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseListAwsClusters._get_unset_required_fields(query_params)) - - return query_params - - class _BaseListAwsNodePools: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/awsClusters/*}/awsNodePools', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.ListAwsNodePoolsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseListAwsNodePools._get_unset_required_fields(query_params)) - - return query_params - - class _BaseRollbackAwsNodePoolUpdate: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/awsClusters/*/awsNodePools/*}:rollback', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.RollbackAwsNodePoolUpdateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseRollbackAwsNodePoolUpdate._get_unset_required_fields(query_params)) - - return query_params - - class _BaseUpdateAwsCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{aws_cluster.name=projects/*/locations/*/awsClusters/*}', - 'body': 'aws_cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.UpdateAwsClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseUpdateAwsCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseUpdateAwsNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{aws_node_pool.name=projects/*/locations/*/awsClusters/*/awsNodePools/*}', - 'body': 'aws_node_pool', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = aws_service.UpdateAwsNodePoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAwsClustersRestTransport._BaseUpdateAwsNodePool._get_unset_required_fields(query_params)) - - return query_params - - class _BaseCancelOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseDeleteOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListOperations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseAwsClustersRestTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/__init__.py deleted file mode 100644 index b27d95ffef58..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AzureClustersClient -from .async_client import AzureClustersAsyncClient - -__all__ = ( - 'AzureClustersClient', - 'AzureClustersAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/async_client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/async_client.py deleted file mode 100644 index 2adc9598d160..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/async_client.py +++ /dev/null @@ -1,3034 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.gke_multicloud_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.gke_multicloud_v1.services.azure_clusters import pagers -from google.cloud.gke_multicloud_v1.types import azure_resources -from google.cloud.gke_multicloud_v1.types import azure_service -from google.cloud.gke_multicloud_v1.types import common_resources -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import AzureClustersTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AzureClustersGrpcAsyncIOTransport -from .client import AzureClustersClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class AzureClustersAsyncClient: - """The AzureClusters API provides a single centrally managed - service to create and manage Anthos clusters that run on Azure - infrastructure. - """ - - _client: AzureClustersClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AzureClustersClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AzureClustersClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AzureClustersClient._DEFAULT_UNIVERSE - - azure_client_path = staticmethod(AzureClustersClient.azure_client_path) - parse_azure_client_path = staticmethod(AzureClustersClient.parse_azure_client_path) - azure_cluster_path = staticmethod(AzureClustersClient.azure_cluster_path) - parse_azure_cluster_path = staticmethod(AzureClustersClient.parse_azure_cluster_path) - azure_node_pool_path = staticmethod(AzureClustersClient.azure_node_pool_path) - parse_azure_node_pool_path = staticmethod(AzureClustersClient.parse_azure_node_pool_path) - azure_server_config_path = staticmethod(AzureClustersClient.azure_server_config_path) - parse_azure_server_config_path = staticmethod(AzureClustersClient.parse_azure_server_config_path) - common_billing_account_path = staticmethod(AzureClustersClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AzureClustersClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AzureClustersClient.common_folder_path) - parse_common_folder_path = staticmethod(AzureClustersClient.parse_common_folder_path) - common_organization_path = staticmethod(AzureClustersClient.common_organization_path) - parse_common_organization_path = staticmethod(AzureClustersClient.parse_common_organization_path) - common_project_path = staticmethod(AzureClustersClient.common_project_path) - parse_common_project_path = staticmethod(AzureClustersClient.parse_common_project_path) - common_location_path = staticmethod(AzureClustersClient.common_location_path) - parse_common_location_path = staticmethod(AzureClustersClient.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: - AzureClustersAsyncClient: The constructed client. - """ - return AzureClustersClient.from_service_account_info.__func__(AzureClustersAsyncClient, 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: - AzureClustersAsyncClient: The constructed client. - """ - return AzureClustersClient.from_service_account_file.__func__(AzureClustersAsyncClient, 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 AzureClustersClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AzureClustersTransport: - """Returns the transport used by the client instance. - - Returns: - AzureClustersTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = AzureClustersClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AzureClustersTransport, Callable[..., AzureClustersTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the azure clusters async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AzureClustersTransport,Callable[..., AzureClustersTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the AzureClustersTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = AzureClustersClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.gkemulticloud_v1.AzureClustersAsyncClient`.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "credentialsType": None, - } - ) - - async def create_azure_client(self, - request: Optional[Union[azure_service.CreateAzureClientRequest, dict]] = None, - *, - parent: Optional[str] = None, - azure_client: Optional[azure_resources.AzureClient] = None, - azure_client_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource on a given Google Cloud project and region. - - ``AzureClient`` resources hold client authentication information - needed by the Anthos Multicloud API to manage Azure resources on - your Azure subscription on your behalf. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_create_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - azure_client = gke_multicloud_v1.AzureClient() - azure_client.tenant_id = "tenant_id_value" - azure_client.application_id = "application_id_value" - - request = gke_multicloud_v1.CreateAzureClientRequest( - parent="parent_value", - azure_client=azure_client, - azure_client_id="azure_client_id_value", - ) - - # Make the request - operation = client.create_azure_client(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAzureClientRequest, dict]]): - The request object. Request message for ``AzureClusters.CreateAzureClient`` - method. - parent (:class:`str`): - Required. The parent location where this - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_client (:class:`google.cloud.gke_multicloud_v1.types.AzureClient`): - Required. The specification of the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - to create. - - This corresponds to the ``azure_client`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_client_id (:class:`str`): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource name formatted as - ``projects//locations//azureClients/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``azure_client_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AzureClient` AzureClient resources hold client authentication information needed by the - Anthos Multi-Cloud API to manage Azure resources on - your Azure subscription. - - When an - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - is created, an AzureClient resource needs to be - provided and all operations on Azure resources - associated to that cluster will authenticate to Azure - services using the given client. - - AzureClient resources are immutable and cannot be - modified upon creation. - - Each AzureClient resource is bound to a single Azure - Active Directory Application and tenant. - - """ - # 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, azure_client, azure_client_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.CreateAzureClientRequest): - request = azure_service.CreateAzureClientRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if azure_client is not None: - request.azure_client = azure_client - if azure_client_id is not None: - request.azure_client_id = azure_client_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_azure_client] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - azure_resources.AzureClient, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_azure_client(self, - request: Optional[Union[azure_service.GetAzureClientRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureClient: - r"""Describes a specific - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - 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 gke_multicloud_v1 - - async def sample_get_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureClientRequest( - name="name_value", - ) - - # Make the request - response = await client.get_azure_client(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureClientRequest, dict]]): - The request object. Request message for ``AzureClusters.GetAzureClient`` - method. - name (:class:`str`): - Required. The name of the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource to describe. - - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - names are formatted as - ``projects//locations//azureClients/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureClient: - AzureClient resources hold client authentication information needed by the - Anthos Multi-Cloud API to manage Azure resources on - your Azure subscription. - - When an - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - is created, an AzureClient resource needs to be - provided and all operations on Azure resources - associated to that cluster will authenticate to Azure - services using the given client. - - AzureClient resources are immutable and cannot be - modified upon creation. - - Each AzureClient resource is bound to a single Azure - Active Directory Application and tenant. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureClientRequest): - request = azure_service.GetAzureClientRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_client] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_azure_clients(self, - request: Optional[Union[azure_service.ListAzureClientsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAzureClientsAsyncPager: - r"""Lists all - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resources on a given Google Cloud project and region. - - .. 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 gke_multicloud_v1 - - async def sample_list_azure_clients(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureClientsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_clients(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest, dict]]): - The request object. Request message for ``AzureClusters.ListAzureClients`` - method. - parent (:class:`str`): - Required. The parent location which owns this collection - of - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClientsAsyncPager: - Response message for AzureClusters.ListAzureClients - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.ListAzureClientsRequest): - request = azure_service.ListAzureClientsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_azure_clients] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAzureClientsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_azure_client(self, - request: Optional[Union[azure_service.DeleteAzureClientRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a specific - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource. - - If the client is used by one or more clusters, deletion will - fail and a ``FAILED_PRECONDITION`` error will be returned. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_delete_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureClientRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_client(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAzureClientRequest, dict]]): - The request object. Request message for ``AzureClusters.DeleteAzureClient`` - method. - name (:class:`str`): - Required. The resource name the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - to delete. - - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - names are formatted as - ``projects//locations//azureClients/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.DeleteAzureClientRequest): - request = azure_service.DeleteAzureClientRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_azure_client] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def create_azure_cluster(self, - request: Optional[Union[azure_service.CreateAzureClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - azure_cluster: Optional[azure_resources.AzureCluster] = None, - azure_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_create_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - azure_cluster = gke_multicloud_v1.AzureCluster() - azure_cluster.azure_region = "azure_region_value" - azure_cluster.resource_group_id = "resource_group_id_value" - azure_cluster.networking.virtual_network_id = "virtual_network_id_value" - azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - azure_cluster.control_plane.version = "version_value" - azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" - azure_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAzureClusterRequest( - parent="parent_value", - azure_cluster=azure_cluster, - azure_cluster_id="azure_cluster_id_value", - ) - - # Make the request - operation = client.create_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAzureClusterRequest, dict]]): - The request object. Request message for ``AzureClusters.CreateAzureCluster`` - method. - parent (:class:`str`): - Required. The parent location where this - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_cluster (:class:`google.cloud.gke_multicloud_v1.types.AzureCluster`): - Required. The specification of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - to create. - - This corresponds to the ``azure_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_cluster_id (:class:`str`): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource name formatted as - ``projects//locations//azureClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``azure_cluster_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AzureCluster` - An Anthos cluster running on Azure. - - """ - # 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, azure_cluster, azure_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.CreateAzureClusterRequest): - request = azure_service.CreateAzureClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if azure_cluster is not None: - request.azure_cluster = azure_cluster - if azure_cluster_id is not None: - request.azure_cluster_id = azure_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_azure_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - azure_resources.AzureCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_azure_cluster(self, - request: Optional[Union[azure_service.UpdateAzureClusterRequest, dict]] = None, - *, - azure_cluster: Optional[azure_resources.AzureCluster] = 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, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - .. 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 gke_multicloud_v1 - - async def sample_update_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - azure_cluster = gke_multicloud_v1.AzureCluster() - azure_cluster.azure_region = "azure_region_value" - azure_cluster.resource_group_id = "resource_group_id_value" - azure_cluster.networking.virtual_network_id = "virtual_network_id_value" - azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - azure_cluster.control_plane.version = "version_value" - azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" - azure_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAzureClusterRequest( - azure_cluster=azure_cluster, - ) - - # Make the request - operation = client.update_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.UpdateAzureClusterRequest, dict]]): - The request object. Request message for ``AzureClusters.UpdateAzureCluster`` - method. - azure_cluster (:class:`google.cloud.gke_multicloud_v1.types.AzureCluster`): - Required. The - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource to update. - - This corresponds to the ``azure_cluster`` 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 path - must be supplied in this field. The elements of the - repeated paths field can only include these fields from - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]: - - - ``description``. - - ``azureClient``. - - ``control_plane.version``. - - ``control_plane.vm_size``. - - ``annotations``. - - ``authorization.admin_users``. - - ``authorization.admin_groups``. - - ``control_plane.root_volume.size_gib``. - - ``azure_services_authentication``. - - ``azure_services_authentication.tenant_id``. - - ``azure_services_authentication.application_id``. - - ``control_plane.proxy_config``. - - ``control_plane.proxy_config.resource_group_id``. - - ``control_plane.proxy_config.secret_id``. - - ``control_plane.ssh_config.authorized_key``. - - ``logging_config.component_config.enable_components`` - - ``monitoring_config.managed_prometheus_config.enabled``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AzureCluster` - An Anthos cluster running on Azure. - - """ - # 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([azure_cluster, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.UpdateAzureClusterRequest): - request = azure_service.UpdateAzureClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if azure_cluster is not None: - request.azure_cluster = azure_cluster - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_azure_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_cluster.name", request.azure_cluster.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - azure_resources.AzureCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_azure_cluster(self, - request: Optional[Union[azure_service.GetAzureClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureCluster: - r"""Describes a specific - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - 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 gke_multicloud_v1 - - async def sample_get_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_azure_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureClusterRequest, dict]]): - The request object. Request message for ``AzureClusters.GetAzureCluster`` - method. - name (:class:`str`): - Required. The name of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource to describe. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureCluster: - An Anthos cluster running on Azure. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureClusterRequest): - request = azure_service.GetAzureClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_azure_clusters(self, - request: Optional[Union[azure_service.ListAzureClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAzureClustersAsyncPager: - r"""Lists all - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resources on a given Google Cloud project and region. - - .. 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 gke_multicloud_v1 - - async def sample_list_azure_clusters(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest, dict]]): - The request object. Request message for ``AzureClusters.ListAzureClusters`` - method. - parent (:class:`str`): - Required. The parent location which owns this collection - of - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClustersAsyncPager: - Response message for AzureClusters.ListAzureClusters - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.ListAzureClustersRequest): - request = azure_service.ListAzureClustersRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_azure_clusters] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAzureClustersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_azure_cluster(self, - request: Optional[Union[azure_service.DeleteAzureClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a specific - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource. - - Fails if the cluster has one or more associated - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_delete_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAzureClusterRequest, dict]]): - The request object. Request message for ``AzureClusters.DeleteAzureCluster`` - method. - name (:class:`str`): - Required. The resource name the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - to delete. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.DeleteAzureClusterRequest): - request = azure_service.DeleteAzureClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_azure_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def generate_azure_cluster_agent_token(self, - request: Optional[Union[azure_service.GenerateAzureClusterAgentTokenRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_service.GenerateAzureClusterAgentTokenResponse: - r"""Generates an access token for a cluster agent. - - .. 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 gke_multicloud_v1 - - async def sample_generate_azure_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAzureClusterAgentTokenRequest( - azure_cluster="azure_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = await client.generate_azure_cluster_agent_token(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenRequest, dict]]): - The request object. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenResponse: - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GenerateAzureClusterAgentTokenRequest): - request = azure_service.GenerateAzureClusterAgentTokenRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_azure_cluster_agent_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_cluster", request.azure_cluster), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def generate_azure_access_token(self, - request: Optional[Union[azure_service.GenerateAzureAccessTokenRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_service.GenerateAzureAccessTokenResponse: - r"""Generates a short-lived access token to authenticate to a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - 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 gke_multicloud_v1 - - async def sample_generate_azure_access_token(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAzureAccessTokenRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = await client.generate_azure_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenRequest, dict]]): - The request object. Request message for - ``AzureClusters.GenerateAzureAccessToken`` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenResponse: - Response message for - AzureClusters.GenerateAzureAccessToken method. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GenerateAzureAccessTokenRequest): - request = azure_service.GenerateAzureAccessTokenRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_azure_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_cluster", request.azure_cluster), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_azure_node_pool(self, - request: Optional[Union[azure_service.CreateAzureNodePoolRequest, dict]] = None, - *, - parent: Optional[str] = None, - azure_node_pool: Optional[azure_resources.AzureNodePool] = None, - azure_node_pool_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool], - attached to a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_create_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - azure_node_pool = gke_multicloud_v1.AzureNodePool() - azure_node_pool.version = "version_value" - azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" - azure_node_pool.subnet_id = "subnet_id_value" - azure_node_pool.autoscaling.min_node_count = 1489 - azure_node_pool.autoscaling.max_node_count = 1491 - azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.CreateAzureNodePoolRequest( - parent="parent_value", - azure_node_pool=azure_node_pool, - azure_node_pool_id="azure_node_pool_id_value", - ) - - # Make the request - operation = client.create_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.CreateAzureNodePoolRequest, dict]]): - The request object. Response message for - ``AzureClusters.CreateAzureNodePool`` method. - parent (:class:`str`): - Required. The - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource where this node pool will be created. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_node_pool (:class:`google.cloud.gke_multicloud_v1.types.AzureNodePool`): - Required. The specification of the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - to create. - - This corresponds to the ``azure_node_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_node_pool_id (:class:`str`): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource name formatted as - ``projects//locations//azureClusters//azureNodePools/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``azure_node_pool_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AzureNodePool` - An Anthos node pool running on Azure. - - """ - # 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, azure_node_pool, azure_node_pool_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.CreateAzureNodePoolRequest): - request = azure_service.CreateAzureNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if azure_node_pool is not None: - request.azure_node_pool = azure_node_pool - if azure_node_pool_id is not None: - request.azure_node_pool_id = azure_node_pool_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_azure_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - azure_resources.AzureNodePool, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_azure_node_pool(self, - request: Optional[Union[azure_service.UpdateAzureNodePoolRequest, dict]] = None, - *, - azure_node_pool: Optional[azure_resources.AzureNodePool] = 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, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates an - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. - - .. 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 gke_multicloud_v1 - - async def sample_update_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - azure_node_pool = gke_multicloud_v1.AzureNodePool() - azure_node_pool.version = "version_value" - azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" - azure_node_pool.subnet_id = "subnet_id_value" - azure_node_pool.autoscaling.min_node_count = 1489 - azure_node_pool.autoscaling.max_node_count = 1491 - azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.UpdateAzureNodePoolRequest( - azure_node_pool=azure_node_pool, - ) - - # Make the request - operation = client.update_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.UpdateAzureNodePoolRequest, dict]]): - The request object. Request message for - ``AzureClusters.UpdateAzureNodePool`` method. - azure_node_pool (:class:`google.cloud.gke_multicloud_v1.types.AzureNodePool`): - Required. The - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource to update. - - This corresponds to the ``azure_node_pool`` 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 path - must be supplied in this field. The elements of the - repeated paths field can only include these fields from - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]: - - \*. ``annotations``. - - - ``version``. - - ``autoscaling.min_node_count``. - - ``autoscaling.max_node_count``. - - ``config.ssh_config.authorized_key``. - - ``management.auto_repair``. - - ``management``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.gke_multicloud_v1.types.AzureNodePool` - An Anthos node pool running on Azure. - - """ - # 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([azure_node_pool, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.UpdateAzureNodePoolRequest): - request = azure_service.UpdateAzureNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if azure_node_pool is not None: - request.azure_node_pool = azure_node_pool - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_azure_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_node_pool.name", request.azure_node_pool.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - azure_resources.AzureNodePool, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_azure_node_pool(self, - request: Optional[Union[azure_service.GetAzureNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureNodePool: - r"""Describes a specific - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - 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 gke_multicloud_v1 - - async def sample_get_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureNodePoolRequest( - name="name_value", - ) - - # Make the request - response = await client.get_azure_node_pool(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureNodePoolRequest, dict]]): - The request object. Request message for ``AzureClusters.GetAzureNodePool`` - method. - name (:class:`str`): - Required. The name of the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource to describe. - - ``AzureNodePool`` names are formatted as - ``projects//locations//azureClusters//azureNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureNodePool: - An Anthos node pool running on Azure. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureNodePoolRequest): - request = azure_service.GetAzureNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_azure_node_pools(self, - request: Optional[Union[azure_service.ListAzureNodePoolsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAzureNodePoolsAsyncPager: - r"""Lists all - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources on a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - .. 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 gke_multicloud_v1 - - async def sample_list_azure_node_pools(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_node_pools(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest, dict]]): - The request object. Request message for ``AzureClusters.ListAzureNodePools`` - method. - parent (:class:`str`): - Required. The parent ``AzureCluster`` which owns this - collection of - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureNodePoolsAsyncPager: - Response message for AzureClusters.ListAzureNodePools - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.ListAzureNodePoolsRequest): - request = azure_service.ListAzureNodePoolsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_azure_node_pools] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAzureNodePoolsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_azure_node_pool(self, - request: Optional[Union[azure_service.DeleteAzureNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a specific - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - async def sample_delete_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.DeleteAzureNodePoolRequest, dict]]): - The request object. Request message for - ``AzureClusters.DeleteAzureNodePool`` method. - name (:class:`str`): - Required. The resource name the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - to delete. - - ``AzureNodePool`` names are formatted as - ``projects//locations//azureClusters//azureNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.DeleteAzureNodePoolRequest): - request = azure_service.DeleteAzureNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_azure_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_azure_open_id_config(self, - request: Optional[Union[azure_service.GetAzureOpenIdConfigRequest, dict]] = None, - *, - azure_cluster: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureOpenIdConfig: - r"""Gets the OIDC discovery document for the cluster. See the - `OpenID Connect Discovery 1.0 - specification `__ - for details. - - .. 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 gke_multicloud_v1 - - async def sample_get_azure_open_id_config(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureOpenIdConfigRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = await client.get_azure_open_id_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureOpenIdConfigRequest, dict]]): - The request object. GetAzureOpenIdConfigRequest gets the - OIDC discovery document for the cluster. - See the OpenID Connect Discovery 1.0 - specification for details. - azure_cluster (:class:`str`): - Required. The AzureCluster, which - owns the OIDC discovery document. - Format: - - projects//locations//azureClusters/ - - This corresponds to the ``azure_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureOpenIdConfig: - AzureOpenIdConfig is an OIDC - discovery document for the cluster. See - the OpenID Connect Discovery 1.0 - specification for details. - - """ - # 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([azure_cluster]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureOpenIdConfigRequest): - request = azure_service.GetAzureOpenIdConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if azure_cluster is not None: - request.azure_cluster = azure_cluster - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_open_id_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_cluster", request.azure_cluster), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_azure_json_web_keys(self, - request: Optional[Union[azure_service.GetAzureJsonWebKeysRequest, dict]] = None, - *, - azure_cluster: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureJsonWebKeys: - r"""Gets the public component of the cluster signing keys - in JSON Web Key format. - - .. 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 gke_multicloud_v1 - - async def sample_get_azure_json_web_keys(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureJsonWebKeysRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = await client.get_azure_json_web_keys(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureJsonWebKeysRequest, dict]]): - The request object. GetAzureJsonWebKeysRequest gets the public component of - the keys used by the cluster to sign token requests. - This will be the jwks_uri for the discover document - returned by getOpenIDConfig. See the OpenID Connect - Discovery 1.0 specification for details. - azure_cluster (:class:`str`): - Required. The AzureCluster, which owns the JsonWebKeys. - Format: - ``projects//locations//azureClusters/`` - - This corresponds to the ``azure_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureJsonWebKeys: - AzureJsonWebKeys is a valid JSON Web - Key Set as specififed in RFC 7517. - - """ - # 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([azure_cluster]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureJsonWebKeysRequest): - request = azure_service.GetAzureJsonWebKeysRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if azure_cluster is not None: - request.azure_cluster = azure_cluster - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_json_web_keys] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_cluster", request.azure_cluster), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_azure_server_config(self, - request: Optional[Union[azure_service.GetAzureServerConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureServerConfig: - r"""Returns information, such as supported Azure regions - and Kubernetes versions, on a given Google Cloud - 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 gke_multicloud_v1 - - async def sample_get_azure_server_config(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureServerConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_azure_server_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.gke_multicloud_v1.types.GetAzureServerConfigRequest, dict]]): - The request object. GetAzureServerConfigRequest gets the - server config of GKE cluster on Azure. - name (:class:`str`): - Required. The name of the - [AzureServerConfig][google.cloud.gkemulticloud.v1.AzureServerConfig] - resource to describe. - - ``AzureServerConfig`` names are formatted as - ``projects//locations//azureServerConfig``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureServerConfig: - AzureServerConfig contains - information about a Google Cloud - location, such as supported Azure - regions and Kubernetes versions. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureServerConfigRequest): - request = azure_service.GetAzureServerConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_azure_server_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_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, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.list_operations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def 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, Union[str, bytes]]] = (), - ) -> 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_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.delete_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - 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, Union[str, bytes]]] = (), - ) -> 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_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self.transport._wrapped_methods[self._client._transport.cancel_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self) -> "AzureClustersAsyncClient": - 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__ = ( - "AzureClustersAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/client.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/client.py deleted file mode 100644 index 1db56d2a8421..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/client.py +++ /dev/null @@ -1,3380 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.gke_multicloud_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.gke_multicloud_v1.services.azure_clusters import pagers -from google.cloud.gke_multicloud_v1.types import azure_resources -from google.cloud.gke_multicloud_v1.types import azure_service -from google.cloud.gke_multicloud_v1.types import common_resources -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import AzureClustersTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AzureClustersGrpcTransport -from .transports.grpc_asyncio import AzureClustersGrpcAsyncIOTransport -from .transports.rest import AzureClustersRestTransport - - -class AzureClustersClientMeta(type): - """Metaclass for the AzureClusters 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[AzureClustersTransport]] - _transport_registry["grpc"] = AzureClustersGrpcTransport - _transport_registry["grpc_asyncio"] = AzureClustersGrpcAsyncIOTransport - _transport_registry["rest"] = AzureClustersRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AzureClustersTransport]: - """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 AzureClustersClient(metaclass=AzureClustersClientMeta): - """The AzureClusters API provides a single centrally managed - service to create and manage Anthos clusters that run on Azure - infrastructure. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "gkemulticloud.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "gkemulticloud.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AzureClustersClient: 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: - AzureClustersClient: 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) -> AzureClustersTransport: - """Returns the transport used by the client instance. - - Returns: - AzureClustersTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def azure_client_path(project: str,location: str,azure_client: str,) -> str: - """Returns a fully-qualified azure_client string.""" - return "projects/{project}/locations/{location}/azureClients/{azure_client}".format(project=project, location=location, azure_client=azure_client, ) - - @staticmethod - def parse_azure_client_path(path: str) -> Dict[str,str]: - """Parses a azure_client path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/azureClients/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def azure_cluster_path(project: str,location: str,azure_cluster: str,) -> str: - """Returns a fully-qualified azure_cluster string.""" - return "projects/{project}/locations/{location}/azureClusters/{azure_cluster}".format(project=project, location=location, azure_cluster=azure_cluster, ) - - @staticmethod - def parse_azure_cluster_path(path: str) -> Dict[str,str]: - """Parses a azure_cluster path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/azureClusters/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def azure_node_pool_path(project: str,location: str,azure_cluster: str,azure_node_pool: str,) -> str: - """Returns a fully-qualified azure_node_pool string.""" - return "projects/{project}/locations/{location}/azureClusters/{azure_cluster}/azureNodePools/{azure_node_pool}".format(project=project, location=location, azure_cluster=azure_cluster, azure_node_pool=azure_node_pool, ) - - @staticmethod - def parse_azure_node_pool_path(path: str) -> Dict[str,str]: - """Parses a azure_node_pool path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/azureClusters/(?P.+?)/azureNodePools/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def azure_server_config_path(project: str,location: str,) -> str: - """Returns a fully-qualified azure_server_config string.""" - return "projects/{project}/locations/{location}/azureServerConfig".format(project=project, location=location, ) - - @staticmethod - def parse_azure_server_config_path(path: str) -> Dict[str,str]: - """Parses a azure_server_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/azureServerConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = AzureClustersClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AzureClustersClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = AzureClustersClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AzureClustersTransport, Callable[..., AzureClustersTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the azure clusters client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AzureClustersTransport,Callable[..., AzureClustersTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the AzureClustersTransport constructor. - If set to None, a transport is chosen automatically. - NOTE: "rest" transport functionality is currently in a - beta state (preview). We welcome your feedback via an - issue in this library's source repository. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AzureClustersClient._read_environment_variables() - self._client_cert_source = AzureClustersClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AzureClustersClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, AzureClustersTransport) - if transport_provided: - # transport is a AzureClustersTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(AzureClustersTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AzureClustersClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[AzureClustersTransport], Callable[..., AzureClustersTransport]] = ( - AzureClustersClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AzureClustersTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.gkemulticloud_v1.AzureClustersClient`.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "credentialsType": None, - } - ) - - def create_azure_client(self, - request: Optional[Union[azure_service.CreateAzureClientRequest, dict]] = None, - *, - parent: Optional[str] = None, - azure_client: Optional[azure_resources.AzureClient] = None, - azure_client_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource on a given Google Cloud project and region. - - ``AzureClient`` resources hold client authentication information - needed by the Anthos Multicloud API to manage Azure resources on - your Azure subscription on your behalf. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_create_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - azure_client = gke_multicloud_v1.AzureClient() - azure_client.tenant_id = "tenant_id_value" - azure_client.application_id = "application_id_value" - - request = gke_multicloud_v1.CreateAzureClientRequest( - parent="parent_value", - azure_client=azure_client, - azure_client_id="azure_client_id_value", - ) - - # Make the request - operation = client.create_azure_client(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.CreateAzureClientRequest, dict]): - The request object. Request message for ``AzureClusters.CreateAzureClient`` - method. - parent (str): - Required. The parent location where this - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_client (google.cloud.gke_multicloud_v1.types.AzureClient): - Required. The specification of the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - to create. - - This corresponds to the ``azure_client`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_client_id (str): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource name formatted as - ``projects//locations//azureClients/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``azure_client_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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.gke_multicloud_v1.types.AzureClient` AzureClient resources hold client authentication information needed by the - Anthos Multi-Cloud API to manage Azure resources on - your Azure subscription. - - When an - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - is created, an AzureClient resource needs to be - provided and all operations on Azure resources - associated to that cluster will authenticate to Azure - services using the given client. - - AzureClient resources are immutable and cannot be - modified upon creation. - - Each AzureClient resource is bound to a single Azure - Active Directory Application and tenant. - - """ - # 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, azure_client, azure_client_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.CreateAzureClientRequest): - request = azure_service.CreateAzureClientRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if azure_client is not None: - request.azure_client = azure_client - if azure_client_id is not None: - request.azure_client_id = azure_client_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_azure_client] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - azure_resources.AzureClient, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_azure_client(self, - request: Optional[Union[azure_service.GetAzureClientRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureClient: - r"""Describes a specific - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - 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 gke_multicloud_v1 - - def sample_get_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureClientRequest( - name="name_value", - ) - - # Make the request - response = client.get_azure_client(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAzureClientRequest, dict]): - The request object. Request message for ``AzureClusters.GetAzureClient`` - method. - name (str): - Required. The name of the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource to describe. - - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - names are formatted as - ``projects//locations//azureClients/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureClient: - AzureClient resources hold client authentication information needed by the - Anthos Multi-Cloud API to manage Azure resources on - your Azure subscription. - - When an - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - is created, an AzureClient resource needs to be - provided and all operations on Azure resources - associated to that cluster will authenticate to Azure - services using the given client. - - AzureClient resources are immutable and cannot be - modified upon creation. - - Each AzureClient resource is bound to a single Azure - Active Directory Application and tenant. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureClientRequest): - request = azure_service.GetAzureClientRequest(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_azure_client] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_azure_clients(self, - request: Optional[Union[azure_service.ListAzureClientsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAzureClientsPager: - r"""Lists all - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resources on a given Google Cloud project and region. - - .. 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 gke_multicloud_v1 - - def sample_list_azure_clients(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureClientsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_clients(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest, dict]): - The request object. Request message for ``AzureClusters.ListAzureClients`` - method. - parent (str): - Required. The parent location which owns this collection - of - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClientsPager: - Response message for AzureClusters.ListAzureClients - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.ListAzureClientsRequest): - request = azure_service.ListAzureClientsRequest(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_azure_clients] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAzureClientsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_azure_client(self, - request: Optional[Union[azure_service.DeleteAzureClientRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a specific - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource. - - If the client is used by one or more clusters, deletion will - fail and a ``FAILED_PRECONDITION`` error will be returned. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_delete_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureClientRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_client(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.DeleteAzureClientRequest, dict]): - The request object. Request message for ``AzureClusters.DeleteAzureClient`` - method. - name (str): - Required. The resource name the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - to delete. - - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - names are formatted as - ``projects//locations//azureClients/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.DeleteAzureClientRequest): - request = azure_service.DeleteAzureClientRequest(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_azure_client] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def create_azure_cluster(self, - request: Optional[Union[azure_service.CreateAzureClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - azure_cluster: Optional[azure_resources.AzureCluster] = None, - azure_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_create_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - azure_cluster = gke_multicloud_v1.AzureCluster() - azure_cluster.azure_region = "azure_region_value" - azure_cluster.resource_group_id = "resource_group_id_value" - azure_cluster.networking.virtual_network_id = "virtual_network_id_value" - azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - azure_cluster.control_plane.version = "version_value" - azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" - azure_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAzureClusterRequest( - parent="parent_value", - azure_cluster=azure_cluster, - azure_cluster_id="azure_cluster_id_value", - ) - - # Make the request - operation = client.create_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.CreateAzureClusterRequest, dict]): - The request object. Request message for ``AzureClusters.CreateAzureCluster`` - method. - parent (str): - Required. The parent location where this - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_cluster (google.cloud.gke_multicloud_v1.types.AzureCluster): - Required. The specification of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - to create. - - This corresponds to the ``azure_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_cluster_id (str): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource name formatted as - ``projects//locations//azureClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``azure_cluster_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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AzureCluster` - An Anthos cluster running on Azure. - - """ - # 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, azure_cluster, azure_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.CreateAzureClusterRequest): - request = azure_service.CreateAzureClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if azure_cluster is not None: - request.azure_cluster = azure_cluster - if azure_cluster_id is not None: - request.azure_cluster_id = azure_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_azure_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - azure_resources.AzureCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_azure_cluster(self, - request: Optional[Union[azure_service.UpdateAzureClusterRequest, dict]] = None, - *, - azure_cluster: Optional[azure_resources.AzureCluster] = 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, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates an - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - .. 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 gke_multicloud_v1 - - def sample_update_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - azure_cluster = gke_multicloud_v1.AzureCluster() - azure_cluster.azure_region = "azure_region_value" - azure_cluster.resource_group_id = "resource_group_id_value" - azure_cluster.networking.virtual_network_id = "virtual_network_id_value" - azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - azure_cluster.control_plane.version = "version_value" - azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" - azure_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAzureClusterRequest( - azure_cluster=azure_cluster, - ) - - # Make the request - operation = client.update_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.UpdateAzureClusterRequest, dict]): - The request object. Request message for ``AzureClusters.UpdateAzureCluster`` - method. - azure_cluster (google.cloud.gke_multicloud_v1.types.AzureCluster): - Required. The - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource to update. - - This corresponds to the ``azure_cluster`` 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 path - must be supplied in this field. The elements of the - repeated paths field can only include these fields from - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]: - - - ``description``. - - ``azureClient``. - - ``control_plane.version``. - - ``control_plane.vm_size``. - - ``annotations``. - - ``authorization.admin_users``. - - ``authorization.admin_groups``. - - ``control_plane.root_volume.size_gib``. - - ``azure_services_authentication``. - - ``azure_services_authentication.tenant_id``. - - ``azure_services_authentication.application_id``. - - ``control_plane.proxy_config``. - - ``control_plane.proxy_config.resource_group_id``. - - ``control_plane.proxy_config.secret_id``. - - ``control_plane.ssh_config.authorized_key``. - - ``logging_config.component_config.enable_components`` - - ``monitoring_config.managed_prometheus_config.enabled``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AzureCluster` - An Anthos cluster running on Azure. - - """ - # 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([azure_cluster, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.UpdateAzureClusterRequest): - request = azure_service.UpdateAzureClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if azure_cluster is not None: - request.azure_cluster = azure_cluster - 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_azure_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_cluster.name", request.azure_cluster.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - azure_resources.AzureCluster, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_azure_cluster(self, - request: Optional[Union[azure_service.GetAzureClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureCluster: - r"""Describes a specific - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - 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 gke_multicloud_v1 - - def sample_get_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_azure_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAzureClusterRequest, dict]): - The request object. Request message for ``AzureClusters.GetAzureCluster`` - method. - name (str): - Required. The name of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource to describe. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureCluster: - An Anthos cluster running on Azure. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureClusterRequest): - request = azure_service.GetAzureClusterRequest(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_azure_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_azure_clusters(self, - request: Optional[Union[azure_service.ListAzureClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAzureClustersPager: - r"""Lists all - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resources on a given Google Cloud project and region. - - .. 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 gke_multicloud_v1 - - def sample_list_azure_clusters(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest, dict]): - The request object. Request message for ``AzureClusters.ListAzureClusters`` - method. - parent (str): - Required. The parent location which owns this collection - of - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClustersPager: - Response message for AzureClusters.ListAzureClusters - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.ListAzureClustersRequest): - request = azure_service.ListAzureClustersRequest(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_azure_clusters] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAzureClustersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_azure_cluster(self, - request: Optional[Union[azure_service.DeleteAzureClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a specific - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource. - - Fails if the cluster has one or more associated - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_delete_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.DeleteAzureClusterRequest, dict]): - The request object. Request message for ``AzureClusters.DeleteAzureCluster`` - method. - name (str): - Required. The resource name the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - to delete. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource - names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.DeleteAzureClusterRequest): - request = azure_service.DeleteAzureClusterRequest(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_azure_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def generate_azure_cluster_agent_token(self, - request: Optional[Union[azure_service.GenerateAzureClusterAgentTokenRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_service.GenerateAzureClusterAgentTokenResponse: - r"""Generates an access token for a cluster agent. - - .. 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 gke_multicloud_v1 - - def sample_generate_azure_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAzureClusterAgentTokenRequest( - azure_cluster="azure_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = client.generate_azure_cluster_agent_token(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenRequest, dict]): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenResponse: - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GenerateAzureClusterAgentTokenRequest): - request = azure_service.GenerateAzureClusterAgentTokenRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_azure_cluster_agent_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_cluster", request.azure_cluster), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_azure_access_token(self, - request: Optional[Union[azure_service.GenerateAzureAccessTokenRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_service.GenerateAzureAccessTokenResponse: - r"""Generates a short-lived access token to authenticate to a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - 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 gke_multicloud_v1 - - def sample_generate_azure_access_token(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAzureAccessTokenRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = client.generate_azure_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenRequest, dict]): - The request object. Request message for - ``AzureClusters.GenerateAzureAccessToken`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenResponse: - Response message for - AzureClusters.GenerateAzureAccessToken method. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GenerateAzureAccessTokenRequest): - request = azure_service.GenerateAzureAccessTokenRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_azure_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_cluster", request.azure_cluster), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_azure_node_pool(self, - request: Optional[Union[azure_service.CreateAzureNodePoolRequest, dict]] = None, - *, - parent: Optional[str] = None, - azure_node_pool: Optional[azure_resources.AzureNodePool] = None, - azure_node_pool_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool], - attached to a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_create_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - azure_node_pool = gke_multicloud_v1.AzureNodePool() - azure_node_pool.version = "version_value" - azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" - azure_node_pool.subnet_id = "subnet_id_value" - azure_node_pool.autoscaling.min_node_count = 1489 - azure_node_pool.autoscaling.max_node_count = 1491 - azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.CreateAzureNodePoolRequest( - parent="parent_value", - azure_node_pool=azure_node_pool, - azure_node_pool_id="azure_node_pool_id_value", - ) - - # Make the request - operation = client.create_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.CreateAzureNodePoolRequest, dict]): - The request object. Response message for - ``AzureClusters.CreateAzureNodePool`` method. - parent (str): - Required. The - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource where this node pool will be created. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_node_pool (google.cloud.gke_multicloud_v1.types.AzureNodePool): - Required. The specification of the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - to create. - - This corresponds to the ``azure_node_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - azure_node_pool_id (str): - Required. A client provided ID the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource name formatted as - ``projects//locations//azureClusters//azureNodePools/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - This corresponds to the ``azure_node_pool_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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AzureNodePool` - An Anthos node pool running on Azure. - - """ - # 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, azure_node_pool, azure_node_pool_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.CreateAzureNodePoolRequest): - request = azure_service.CreateAzureNodePoolRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if azure_node_pool is not None: - request.azure_node_pool = azure_node_pool - if azure_node_pool_id is not None: - request.azure_node_pool_id = azure_node_pool_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_azure_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - azure_resources.AzureNodePool, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_azure_node_pool(self, - request: Optional[Union[azure_service.UpdateAzureNodePoolRequest, dict]] = None, - *, - azure_node_pool: Optional[azure_resources.AzureNodePool] = 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, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates an - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. - - .. 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 gke_multicloud_v1 - - def sample_update_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - azure_node_pool = gke_multicloud_v1.AzureNodePool() - azure_node_pool.version = "version_value" - azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" - azure_node_pool.subnet_id = "subnet_id_value" - azure_node_pool.autoscaling.min_node_count = 1489 - azure_node_pool.autoscaling.max_node_count = 1491 - azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.UpdateAzureNodePoolRequest( - azure_node_pool=azure_node_pool, - ) - - # Make the request - operation = client.update_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.UpdateAzureNodePoolRequest, dict]): - The request object. Request message for - ``AzureClusters.UpdateAzureNodePool`` method. - azure_node_pool (google.cloud.gke_multicloud_v1.types.AzureNodePool): - Required. The - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource to update. - - This corresponds to the ``azure_node_pool`` 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 path - must be supplied in this field. The elements of the - repeated paths field can only include these fields from - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]: - - \*. ``annotations``. - - - ``version``. - - ``autoscaling.min_node_count``. - - ``autoscaling.max_node_count``. - - ``config.ssh_config.authorized_key``. - - ``management.auto_repair``. - - ``management``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.gke_multicloud_v1.types.AzureNodePool` - An Anthos node pool running on Azure. - - """ - # 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([azure_node_pool, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.UpdateAzureNodePoolRequest): - request = azure_service.UpdateAzureNodePoolRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if azure_node_pool is not None: - request.azure_node_pool = azure_node_pool - 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_azure_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_node_pool.name", request.azure_node_pool.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - azure_resources.AzureNodePool, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_azure_node_pool(self, - request: Optional[Union[azure_service.GetAzureNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureNodePool: - r"""Describes a specific - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - 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 gke_multicloud_v1 - - def sample_get_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureNodePoolRequest( - name="name_value", - ) - - # Make the request - response = client.get_azure_node_pool(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAzureNodePoolRequest, dict]): - The request object. Request message for ``AzureClusters.GetAzureNodePool`` - method. - name (str): - Required. The name of the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource to describe. - - ``AzureNodePool`` names are formatted as - ``projects//locations//azureClusters//azureNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureNodePool: - An Anthos node pool running on Azure. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureNodePoolRequest): - request = azure_service.GetAzureNodePoolRequest(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_azure_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_azure_node_pools(self, - request: Optional[Union[azure_service.ListAzureNodePoolsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAzureNodePoolsPager: - r"""Lists all - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources on a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - .. 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 gke_multicloud_v1 - - def sample_list_azure_node_pools(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_node_pools(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest, dict]): - The request object. Request message for ``AzureClusters.ListAzureNodePools`` - method. - parent (str): - Required. The parent ``AzureCluster`` which owns this - collection of - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureNodePoolsPager: - Response message for AzureClusters.ListAzureNodePools - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.ListAzureNodePoolsRequest): - request = azure_service.ListAzureNodePoolsRequest(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_azure_node_pools] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAzureNodePoolsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_azure_node_pool(self, - request: Optional[Union[azure_service.DeleteAzureNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a specific - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - .. 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 gke_multicloud_v1 - - def sample_delete_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.DeleteAzureNodePoolRequest, dict]): - The request object. Request message for - ``AzureClusters.DeleteAzureNodePool`` method. - name (str): - Required. The resource name the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - to delete. - - ``AzureNodePool`` names are formatted as - ``projects//locations//azureClusters//azureNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.DeleteAzureNodePoolRequest): - request = azure_service.DeleteAzureNodePoolRequest(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_azure_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common_resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_azure_open_id_config(self, - request: Optional[Union[azure_service.GetAzureOpenIdConfigRequest, dict]] = None, - *, - azure_cluster: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureOpenIdConfig: - r"""Gets the OIDC discovery document for the cluster. See the - `OpenID Connect Discovery 1.0 - specification `__ - for details. - - .. 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 gke_multicloud_v1 - - def sample_get_azure_open_id_config(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureOpenIdConfigRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = client.get_azure_open_id_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAzureOpenIdConfigRequest, dict]): - The request object. GetAzureOpenIdConfigRequest gets the - OIDC discovery document for the cluster. - See the OpenID Connect Discovery 1.0 - specification for details. - azure_cluster (str): - Required. The AzureCluster, which - owns the OIDC discovery document. - Format: - - projects//locations//azureClusters/ - - This corresponds to the ``azure_cluster`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureOpenIdConfig: - AzureOpenIdConfig is an OIDC - discovery document for the cluster. See - the OpenID Connect Discovery 1.0 - specification for details. - - """ - # 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([azure_cluster]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureOpenIdConfigRequest): - request = azure_service.GetAzureOpenIdConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if azure_cluster is not None: - request.azure_cluster = azure_cluster - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_azure_open_id_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_cluster", request.azure_cluster), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_azure_json_web_keys(self, - request: Optional[Union[azure_service.GetAzureJsonWebKeysRequest, dict]] = None, - *, - azure_cluster: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureJsonWebKeys: - r"""Gets the public component of the cluster signing keys - in JSON Web Key format. - - .. 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 gke_multicloud_v1 - - def sample_get_azure_json_web_keys(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureJsonWebKeysRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = client.get_azure_json_web_keys(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAzureJsonWebKeysRequest, dict]): - The request object. GetAzureJsonWebKeysRequest gets the public component of - the keys used by the cluster to sign token requests. - This will be the jwks_uri for the discover document - returned by getOpenIDConfig. See the OpenID Connect - Discovery 1.0 specification for details. - azure_cluster (str): - Required. The AzureCluster, which owns the JsonWebKeys. - Format: - ``projects//locations//azureClusters/`` - - This corresponds to the ``azure_cluster`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureJsonWebKeys: - AzureJsonWebKeys is a valid JSON Web - Key Set as specififed in RFC 7517. - - """ - # 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([azure_cluster]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureJsonWebKeysRequest): - request = azure_service.GetAzureJsonWebKeysRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if azure_cluster is not None: - request.azure_cluster = azure_cluster - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_azure_json_web_keys] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("azure_cluster", request.azure_cluster), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_azure_server_config(self, - request: Optional[Union[azure_service.GetAzureServerConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> azure_resources.AzureServerConfig: - r"""Returns information, such as supported Azure regions - and Kubernetes versions, on a given Google Cloud - 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 gke_multicloud_v1 - - def sample_get_azure_server_config(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureServerConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_azure_server_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.gke_multicloud_v1.types.GetAzureServerConfigRequest, dict]): - The request object. GetAzureServerConfigRequest gets the - server config of GKE cluster on Azure. - name (str): - Required. The name of the - [AzureServerConfig][google.cloud.gkemulticloud.v1.AzureServerConfig] - resource to describe. - - ``AzureServerConfig`` names are formatted as - ``projects//locations//azureServerConfig``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.gke_multicloud_v1.types.AzureServerConfig: - AzureServerConfig contains - information about a Google Cloud - location, such as supported Azure - regions and Kubernetes versions. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, azure_service.GetAzureServerConfigRequest): - request = azure_service.GetAzureServerConfigRequest(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_azure_server_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AzureClustersClient": - 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, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.list_operations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def 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, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.delete_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - 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, Union[str, bytes]]] = (), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 = self._transport._wrapped_methods[self._transport.cancel_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AzureClustersClient", -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/pagers.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/pagers.py deleted file mode 100644 index bf54373beaf2..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/pagers.py +++ /dev/null @@ -1,445 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.cloud.gke_multicloud_v1.types import azure_resources -from google.cloud.gke_multicloud_v1.types import azure_service - - -class ListAzureClientsPager: - """A pager for iterating through ``list_azure_clients`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``azure_clients`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAzureClients`` requests and continue to iterate - through the ``azure_clients`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse` - 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[..., azure_service.ListAzureClientsResponse], - request: azure_service.ListAzureClientsRequest, - response: azure_service.ListAzureClientsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = azure_service.ListAzureClientsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[azure_service.ListAzureClientsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[azure_resources.AzureClient]: - for page in self.pages: - yield from page.azure_clients - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAzureClientsAsyncPager: - """A pager for iterating through ``list_azure_clients`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``azure_clients`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAzureClients`` requests and continue to iterate - through the ``azure_clients`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse` - 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[azure_service.ListAzureClientsResponse]], - request: azure_service.ListAzureClientsRequest, - response: azure_service.ListAzureClientsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAzureClientsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = azure_service.ListAzureClientsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[azure_service.ListAzureClientsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[azure_resources.AzureClient]: - async def async_generator(): - async for page in self.pages: - for response in page.azure_clients: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAzureClustersPager: - """A pager for iterating through ``list_azure_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``azure_clusters`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAzureClusters`` requests and continue to iterate - through the ``azure_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse` - 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[..., azure_service.ListAzureClustersResponse], - request: azure_service.ListAzureClustersRequest, - response: azure_service.ListAzureClustersResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = azure_service.ListAzureClustersRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[azure_service.ListAzureClustersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[azure_resources.AzureCluster]: - for page in self.pages: - yield from page.azure_clusters - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAzureClustersAsyncPager: - """A pager for iterating through ``list_azure_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``azure_clusters`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAzureClusters`` requests and continue to iterate - through the ``azure_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse` - 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[azure_service.ListAzureClustersResponse]], - request: azure_service.ListAzureClustersRequest, - response: azure_service.ListAzureClustersResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAzureClustersResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = azure_service.ListAzureClustersRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[azure_service.ListAzureClustersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[azure_resources.AzureCluster]: - async def async_generator(): - async for page in self.pages: - for response in page.azure_clusters: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAzureNodePoolsPager: - """A pager for iterating through ``list_azure_node_pools`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``azure_node_pools`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAzureNodePools`` requests and continue to iterate - through the ``azure_node_pools`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse` - 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[..., azure_service.ListAzureNodePoolsResponse], - request: azure_service.ListAzureNodePoolsRequest, - response: azure_service.ListAzureNodePoolsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = azure_service.ListAzureNodePoolsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[azure_service.ListAzureNodePoolsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[azure_resources.AzureNodePool]: - for page in self.pages: - yield from page.azure_node_pools - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAzureNodePoolsAsyncPager: - """A pager for iterating through ``list_azure_node_pools`` requests. - - This class thinly wraps an initial - :class:`google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``azure_node_pools`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAzureNodePools`` requests and continue to iterate - through the ``azure_node_pools`` field on the - corresponding responses. - - All the usual :class:`google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse` - 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[azure_service.ListAzureNodePoolsResponse]], - request: azure_service.ListAzureNodePoolsRequest, - response: azure_service.ListAzureNodePoolsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest): - The initial request object. - response (google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = azure_service.ListAzureNodePoolsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[azure_service.ListAzureNodePoolsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[azure_resources.AzureNodePool]: - async def async_generator(): - async for page in self.pages: - for response in page.azure_node_pools: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/README.rst b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/README.rst deleted file mode 100644 index cc9731adcaaa..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AzureClustersTransport` is the ABC for all transports. -- public child `AzureClustersGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AzureClustersGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAzureClustersRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AzureClustersRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/__init__.py deleted file mode 100644 index d5596ee4b241..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AzureClustersTransport -from .grpc import AzureClustersGrpcTransport -from .grpc_asyncio import AzureClustersGrpcAsyncIOTransport -from .rest import AzureClustersRestTransport -from .rest import AzureClustersRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AzureClustersTransport]] -_transport_registry['grpc'] = AzureClustersGrpcTransport -_transport_registry['grpc_asyncio'] = AzureClustersGrpcAsyncIOTransport -_transport_registry['rest'] = AzureClustersRestTransport - -__all__ = ( - 'AzureClustersTransport', - 'AzureClustersGrpcTransport', - 'AzureClustersGrpcAsyncIOTransport', - 'AzureClustersRestTransport', - 'AzureClustersRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/base.py deleted file mode 100644 index 06191ddf281c..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/base.py +++ /dev/null @@ -1,569 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.gke_multicloud_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.gke_multicloud_v1.types import azure_resources -from google.cloud.gke_multicloud_v1.types import azure_service -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AzureClustersTransport(abc.ABC): - """Abstract transport class for AzureClusters.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'gkemulticloud.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_azure_client: gapic_v1.method.wrap_method( - self.create_azure_client, - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_client: gapic_v1.method.wrap_method( - self.get_azure_client, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_azure_clients: gapic_v1.method.wrap_method( - self.list_azure_clients, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_azure_client: gapic_v1.method.wrap_method( - self.delete_azure_client, - default_timeout=60.0, - client_info=client_info, - ), - self.create_azure_cluster: gapic_v1.method.wrap_method( - self.create_azure_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_azure_cluster: gapic_v1.method.wrap_method( - self.update_azure_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_cluster: gapic_v1.method.wrap_method( - self.get_azure_cluster, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_azure_clusters: gapic_v1.method.wrap_method( - self.list_azure_clusters, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_azure_cluster: gapic_v1.method.wrap_method( - self.delete_azure_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_azure_cluster_agent_token: gapic_v1.method.wrap_method( - self.generate_azure_cluster_agent_token, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_azure_access_token: gapic_v1.method.wrap_method( - self.generate_azure_access_token, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_azure_node_pool: gapic_v1.method.wrap_method( - self.create_azure_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.update_azure_node_pool: gapic_v1.method.wrap_method( - self.update_azure_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_node_pool: gapic_v1.method.wrap_method( - self.get_azure_node_pool, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_azure_node_pools: gapic_v1.method.wrap_method( - self.list_azure_node_pools, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_azure_node_pool: gapic_v1.method.wrap_method( - self.delete_azure_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_open_id_config: gapic_v1.method.wrap_method( - self.get_azure_open_id_config, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_json_web_keys: gapic_v1.method.wrap_method( - self.get_azure_json_web_keys, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_server_config: gapic_v1.method.wrap_method( - self.get_azure_server_config, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - 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 create_azure_client(self) -> Callable[ - [azure_service.CreateAzureClientRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_azure_client(self) -> Callable[ - [azure_service.GetAzureClientRequest], - Union[ - azure_resources.AzureClient, - Awaitable[azure_resources.AzureClient] - ]]: - raise NotImplementedError() - - @property - def list_azure_clients(self) -> Callable[ - [azure_service.ListAzureClientsRequest], - Union[ - azure_service.ListAzureClientsResponse, - Awaitable[azure_service.ListAzureClientsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_azure_client(self) -> Callable[ - [azure_service.DeleteAzureClientRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_azure_cluster(self) -> Callable[ - [azure_service.CreateAzureClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_azure_cluster(self) -> Callable[ - [azure_service.UpdateAzureClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_azure_cluster(self) -> Callable[ - [azure_service.GetAzureClusterRequest], - Union[ - azure_resources.AzureCluster, - Awaitable[azure_resources.AzureCluster] - ]]: - raise NotImplementedError() - - @property - def list_azure_clusters(self) -> Callable[ - [azure_service.ListAzureClustersRequest], - Union[ - azure_service.ListAzureClustersResponse, - Awaitable[azure_service.ListAzureClustersResponse] - ]]: - raise NotImplementedError() - - @property - def delete_azure_cluster(self) -> Callable[ - [azure_service.DeleteAzureClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def generate_azure_cluster_agent_token(self) -> Callable[ - [azure_service.GenerateAzureClusterAgentTokenRequest], - Union[ - azure_service.GenerateAzureClusterAgentTokenResponse, - Awaitable[azure_service.GenerateAzureClusterAgentTokenResponse] - ]]: - raise NotImplementedError() - - @property - def generate_azure_access_token(self) -> Callable[ - [azure_service.GenerateAzureAccessTokenRequest], - Union[ - azure_service.GenerateAzureAccessTokenResponse, - Awaitable[azure_service.GenerateAzureAccessTokenResponse] - ]]: - raise NotImplementedError() - - @property - def create_azure_node_pool(self) -> Callable[ - [azure_service.CreateAzureNodePoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_azure_node_pool(self) -> Callable[ - [azure_service.UpdateAzureNodePoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_azure_node_pool(self) -> Callable[ - [azure_service.GetAzureNodePoolRequest], - Union[ - azure_resources.AzureNodePool, - Awaitable[azure_resources.AzureNodePool] - ]]: - raise NotImplementedError() - - @property - def list_azure_node_pools(self) -> Callable[ - [azure_service.ListAzureNodePoolsRequest], - Union[ - azure_service.ListAzureNodePoolsResponse, - Awaitable[azure_service.ListAzureNodePoolsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_azure_node_pool(self) -> Callable[ - [azure_service.DeleteAzureNodePoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_azure_open_id_config(self) -> Callable[ - [azure_service.GetAzureOpenIdConfigRequest], - Union[ - azure_resources.AzureOpenIdConfig, - Awaitable[azure_resources.AzureOpenIdConfig] - ]]: - raise NotImplementedError() - - @property - def get_azure_json_web_keys(self) -> Callable[ - [azure_service.GetAzureJsonWebKeysRequest], - Union[ - azure_resources.AzureJsonWebKeys, - Awaitable[azure_resources.AzureJsonWebKeys] - ]]: - raise NotImplementedError() - - @property - def get_azure_server_config(self) -> Callable[ - [azure_service.GetAzureServerConfigRequest], - Union[ - azure_resources.AzureServerConfig, - Awaitable[azure_resources.AzureServerConfig] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AzureClustersTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc.py deleted file mode 100644 index 1f02eb54c078..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc.py +++ /dev/null @@ -1,981 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -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 -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.cloud.gke_multicloud_v1.types import azure_resources -from google.cloud.gke_multicloud_v1.types import azure_service -from google.longrunning import operations_pb2 # type: ignore -from .base import AzureClustersTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": client_call_details.method, - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AzureClustersGrpcTransport(AzureClustersTransport): - """gRPC backend transport for AzureClusters. - - The AzureClusters API provides a single centrally managed - service to create and manage Anthos clusters that run on Azure - infrastructure. - - 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 = 'gkemulticloud.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'gkemulticloud.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._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_azure_client(self) -> Callable[ - [azure_service.CreateAzureClientRequest], - operations_pb2.Operation]: - r"""Return a callable for the create azure client method over gRPC. - - Creates a new - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource on a given Google Cloud project and region. - - ``AzureClient`` resources hold client authentication information - needed by the Anthos Multicloud API to manage Azure resources on - your Azure subscription on your behalf. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAzureClientRequest], - ~.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_azure_client' not in self._stubs: - self._stubs['create_azure_client'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureClient', - request_serializer=azure_service.CreateAzureClientRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_azure_client'] - - @property - def get_azure_client(self) -> Callable[ - [azure_service.GetAzureClientRequest], - azure_resources.AzureClient]: - r"""Return a callable for the get azure client method over gRPC. - - Describes a specific - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource. - - Returns: - Callable[[~.GetAzureClientRequest], - ~.AzureClient]: - 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_azure_client' not in self._stubs: - self._stubs['get_azure_client'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureClient', - request_serializer=azure_service.GetAzureClientRequest.serialize, - response_deserializer=azure_resources.AzureClient.deserialize, - ) - return self._stubs['get_azure_client'] - - @property - def list_azure_clients(self) -> Callable[ - [azure_service.ListAzureClientsRequest], - azure_service.ListAzureClientsResponse]: - r"""Return a callable for the list azure clients method over gRPC. - - Lists all - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resources on a given Google Cloud project and region. - - Returns: - Callable[[~.ListAzureClientsRequest], - ~.ListAzureClientsResponse]: - 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_azure_clients' not in self._stubs: - self._stubs['list_azure_clients'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureClients', - request_serializer=azure_service.ListAzureClientsRequest.serialize, - response_deserializer=azure_service.ListAzureClientsResponse.deserialize, - ) - return self._stubs['list_azure_clients'] - - @property - def delete_azure_client(self) -> Callable[ - [azure_service.DeleteAzureClientRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete azure client method over gRPC. - - Deletes a specific - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource. - - If the client is used by one or more clusters, deletion will - fail and a ``FAILED_PRECONDITION`` error will be returned. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAzureClientRequest], - ~.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_azure_client' not in self._stubs: - self._stubs['delete_azure_client'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureClient', - request_serializer=azure_service.DeleteAzureClientRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_azure_client'] - - @property - def create_azure_cluster(self) -> Callable[ - [azure_service.CreateAzureClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the create azure cluster method over gRPC. - - Creates a new - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAzureClusterRequest], - ~.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_azure_cluster' not in self._stubs: - self._stubs['create_azure_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureCluster', - request_serializer=azure_service.CreateAzureClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_azure_cluster'] - - @property - def update_azure_cluster(self) -> Callable[ - [azure_service.UpdateAzureClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the update azure cluster method over gRPC. - - Updates an - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - Returns: - Callable[[~.UpdateAzureClusterRequest], - ~.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_azure_cluster' not in self._stubs: - self._stubs['update_azure_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/UpdateAzureCluster', - request_serializer=azure_service.UpdateAzureClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_azure_cluster'] - - @property - def get_azure_cluster(self) -> Callable[ - [azure_service.GetAzureClusterRequest], - azure_resources.AzureCluster]: - r"""Return a callable for the get azure cluster method over gRPC. - - Describes a specific - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource. - - Returns: - Callable[[~.GetAzureClusterRequest], - ~.AzureCluster]: - 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_azure_cluster' not in self._stubs: - self._stubs['get_azure_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureCluster', - request_serializer=azure_service.GetAzureClusterRequest.serialize, - response_deserializer=azure_resources.AzureCluster.deserialize, - ) - return self._stubs['get_azure_cluster'] - - @property - def list_azure_clusters(self) -> Callable[ - [azure_service.ListAzureClustersRequest], - azure_service.ListAzureClustersResponse]: - r"""Return a callable for the list azure clusters method over gRPC. - - Lists all - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resources on a given Google Cloud project and region. - - Returns: - Callable[[~.ListAzureClustersRequest], - ~.ListAzureClustersResponse]: - 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_azure_clusters' not in self._stubs: - self._stubs['list_azure_clusters'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureClusters', - request_serializer=azure_service.ListAzureClustersRequest.serialize, - response_deserializer=azure_service.ListAzureClustersResponse.deserialize, - ) - return self._stubs['list_azure_clusters'] - - @property - def delete_azure_cluster(self) -> Callable[ - [azure_service.DeleteAzureClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete azure cluster method over gRPC. - - Deletes a specific - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource. - - Fails if the cluster has one or more associated - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAzureClusterRequest], - ~.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_azure_cluster' not in self._stubs: - self._stubs['delete_azure_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureCluster', - request_serializer=azure_service.DeleteAzureClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_azure_cluster'] - - @property - def generate_azure_cluster_agent_token(self) -> Callable[ - [azure_service.GenerateAzureClusterAgentTokenRequest], - azure_service.GenerateAzureClusterAgentTokenResponse]: - r"""Return a callable for the generate azure cluster agent - token method over gRPC. - - Generates an access token for a cluster agent. - - Returns: - Callable[[~.GenerateAzureClusterAgentTokenRequest], - ~.GenerateAzureClusterAgentTokenResponse]: - 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_azure_cluster_agent_token' not in self._stubs: - self._stubs['generate_azure_cluster_agent_token'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GenerateAzureClusterAgentToken', - request_serializer=azure_service.GenerateAzureClusterAgentTokenRequest.serialize, - response_deserializer=azure_service.GenerateAzureClusterAgentTokenResponse.deserialize, - ) - return self._stubs['generate_azure_cluster_agent_token'] - - @property - def generate_azure_access_token(self) -> Callable[ - [azure_service.GenerateAzureAccessTokenRequest], - azure_service.GenerateAzureAccessTokenResponse]: - r"""Return a callable for the generate azure access token method over gRPC. - - Generates a short-lived access token to authenticate to a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource. - - Returns: - Callable[[~.GenerateAzureAccessTokenRequest], - ~.GenerateAzureAccessTokenResponse]: - 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_azure_access_token' not in self._stubs: - self._stubs['generate_azure_access_token'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GenerateAzureAccessToken', - request_serializer=azure_service.GenerateAzureAccessTokenRequest.serialize, - response_deserializer=azure_service.GenerateAzureAccessTokenResponse.deserialize, - ) - return self._stubs['generate_azure_access_token'] - - @property - def create_azure_node_pool(self) -> Callable[ - [azure_service.CreateAzureNodePoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the create azure node pool method over gRPC. - - Creates a new - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool], - attached to a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAzureNodePoolRequest], - ~.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_azure_node_pool' not in self._stubs: - self._stubs['create_azure_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureNodePool', - request_serializer=azure_service.CreateAzureNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_azure_node_pool'] - - @property - def update_azure_node_pool(self) -> Callable[ - [azure_service.UpdateAzureNodePoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the update azure node pool method over gRPC. - - Updates an - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. - - Returns: - Callable[[~.UpdateAzureNodePoolRequest], - ~.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_azure_node_pool' not in self._stubs: - self._stubs['update_azure_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/UpdateAzureNodePool', - request_serializer=azure_service.UpdateAzureNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_azure_node_pool'] - - @property - def get_azure_node_pool(self) -> Callable[ - [azure_service.GetAzureNodePoolRequest], - azure_resources.AzureNodePool]: - r"""Return a callable for the get azure node pool method over gRPC. - - Describes a specific - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource. - - Returns: - Callable[[~.GetAzureNodePoolRequest], - ~.AzureNodePool]: - 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_azure_node_pool' not in self._stubs: - self._stubs['get_azure_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureNodePool', - request_serializer=azure_service.GetAzureNodePoolRequest.serialize, - response_deserializer=azure_resources.AzureNodePool.deserialize, - ) - return self._stubs['get_azure_node_pool'] - - @property - def list_azure_node_pools(self) -> Callable[ - [azure_service.ListAzureNodePoolsRequest], - azure_service.ListAzureNodePoolsResponse]: - r"""Return a callable for the list azure node pools method over gRPC. - - Lists all - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources on a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - Returns: - Callable[[~.ListAzureNodePoolsRequest], - ~.ListAzureNodePoolsResponse]: - 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_azure_node_pools' not in self._stubs: - self._stubs['list_azure_node_pools'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureNodePools', - request_serializer=azure_service.ListAzureNodePoolsRequest.serialize, - response_deserializer=azure_service.ListAzureNodePoolsResponse.deserialize, - ) - return self._stubs['list_azure_node_pools'] - - @property - def delete_azure_node_pool(self) -> Callable[ - [azure_service.DeleteAzureNodePoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete azure node pool method over gRPC. - - Deletes a specific - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAzureNodePoolRequest], - ~.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_azure_node_pool' not in self._stubs: - self._stubs['delete_azure_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureNodePool', - request_serializer=azure_service.DeleteAzureNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_azure_node_pool'] - - @property - def get_azure_open_id_config(self) -> Callable[ - [azure_service.GetAzureOpenIdConfigRequest], - azure_resources.AzureOpenIdConfig]: - r"""Return a callable for the get azure open id config method over gRPC. - - Gets the OIDC discovery document for the cluster. See the - `OpenID Connect Discovery 1.0 - specification `__ - for details. - - Returns: - Callable[[~.GetAzureOpenIdConfigRequest], - ~.AzureOpenIdConfig]: - 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_azure_open_id_config' not in self._stubs: - self._stubs['get_azure_open_id_config'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureOpenIdConfig', - request_serializer=azure_service.GetAzureOpenIdConfigRequest.serialize, - response_deserializer=azure_resources.AzureOpenIdConfig.deserialize, - ) - return self._stubs['get_azure_open_id_config'] - - @property - def get_azure_json_web_keys(self) -> Callable[ - [azure_service.GetAzureJsonWebKeysRequest], - azure_resources.AzureJsonWebKeys]: - r"""Return a callable for the get azure json web keys method over gRPC. - - Gets the public component of the cluster signing keys - in JSON Web Key format. - - Returns: - Callable[[~.GetAzureJsonWebKeysRequest], - ~.AzureJsonWebKeys]: - 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_azure_json_web_keys' not in self._stubs: - self._stubs['get_azure_json_web_keys'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureJsonWebKeys', - request_serializer=azure_service.GetAzureJsonWebKeysRequest.serialize, - response_deserializer=azure_resources.AzureJsonWebKeys.deserialize, - ) - return self._stubs['get_azure_json_web_keys'] - - @property - def get_azure_server_config(self) -> Callable[ - [azure_service.GetAzureServerConfigRequest], - azure_resources.AzureServerConfig]: - r"""Return a callable for the get azure server config method over gRPC. - - Returns information, such as supported Azure regions - and Kubernetes versions, on a given Google Cloud - location. - - Returns: - Callable[[~.GetAzureServerConfigRequest], - ~.AzureServerConfig]: - 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_azure_server_config' not in self._stubs: - self._stubs['get_azure_server_config'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureServerConfig', - request_serializer=azure_service.GetAzureServerConfigRequest.serialize, - response_deserializer=azure_resources.AzureServerConfig.deserialize, - ) - return self._stubs['get_azure_server_config'] - - def close(self): - self._logged_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._logged_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._logged_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._logged_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._logged_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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AzureClustersGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc_asyncio.py deleted file mode 100644 index 65631795c139..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/grpc_asyncio.py +++ /dev/null @@ -1,1210 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -import logging as std_logging -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.gke_multicloud_v1.types import azure_resources -from google.cloud.gke_multicloud_v1.types import azure_service -from google.longrunning import operations_pb2 # type: ignore -from .base import AzureClustersTransport, DEFAULT_CLIENT_INFO -from .grpc import AzureClustersGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AzureClustersGrpcAsyncIOTransport(AzureClustersTransport): - """gRPC AsyncIO backend transport for AzureClusters. - - The AzureClusters API provides a single centrally managed - service to create and manage Anthos clusters that run on Azure - infrastructure. - - 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 = 'gkemulticloud.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'gkemulticloud.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_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._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_azure_client(self) -> Callable[ - [azure_service.CreateAzureClientRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create azure client method over gRPC. - - Creates a new - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource on a given Google Cloud project and region. - - ``AzureClient`` resources hold client authentication information - needed by the Anthos Multicloud API to manage Azure resources on - your Azure subscription on your behalf. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAzureClientRequest], - 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_azure_client' not in self._stubs: - self._stubs['create_azure_client'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureClient', - request_serializer=azure_service.CreateAzureClientRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_azure_client'] - - @property - def get_azure_client(self) -> Callable[ - [azure_service.GetAzureClientRequest], - Awaitable[azure_resources.AzureClient]]: - r"""Return a callable for the get azure client method over gRPC. - - Describes a specific - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource. - - Returns: - Callable[[~.GetAzureClientRequest], - Awaitable[~.AzureClient]]: - 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_azure_client' not in self._stubs: - self._stubs['get_azure_client'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureClient', - request_serializer=azure_service.GetAzureClientRequest.serialize, - response_deserializer=azure_resources.AzureClient.deserialize, - ) - return self._stubs['get_azure_client'] - - @property - def list_azure_clients(self) -> Callable[ - [azure_service.ListAzureClientsRequest], - Awaitable[azure_service.ListAzureClientsResponse]]: - r"""Return a callable for the list azure clients method over gRPC. - - Lists all - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resources on a given Google Cloud project and region. - - Returns: - Callable[[~.ListAzureClientsRequest], - Awaitable[~.ListAzureClientsResponse]]: - 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_azure_clients' not in self._stubs: - self._stubs['list_azure_clients'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureClients', - request_serializer=azure_service.ListAzureClientsRequest.serialize, - response_deserializer=azure_service.ListAzureClientsResponse.deserialize, - ) - return self._stubs['list_azure_clients'] - - @property - def delete_azure_client(self) -> Callable[ - [azure_service.DeleteAzureClientRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete azure client method over gRPC. - - Deletes a specific - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource. - - If the client is used by one or more clusters, deletion will - fail and a ``FAILED_PRECONDITION`` error will be returned. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAzureClientRequest], - 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_azure_client' not in self._stubs: - self._stubs['delete_azure_client'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureClient', - request_serializer=azure_service.DeleteAzureClientRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_azure_client'] - - @property - def create_azure_cluster(self) -> Callable[ - [azure_service.CreateAzureClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create azure cluster method over gRPC. - - Creates a new - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource on a given Google Cloud Platform project and region. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAzureClusterRequest], - 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_azure_cluster' not in self._stubs: - self._stubs['create_azure_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureCluster', - request_serializer=azure_service.CreateAzureClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_azure_cluster'] - - @property - def update_azure_cluster(self) -> Callable[ - [azure_service.UpdateAzureClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update azure cluster method over gRPC. - - Updates an - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - Returns: - Callable[[~.UpdateAzureClusterRequest], - 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_azure_cluster' not in self._stubs: - self._stubs['update_azure_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/UpdateAzureCluster', - request_serializer=azure_service.UpdateAzureClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_azure_cluster'] - - @property - def get_azure_cluster(self) -> Callable[ - [azure_service.GetAzureClusterRequest], - Awaitable[azure_resources.AzureCluster]]: - r"""Return a callable for the get azure cluster method over gRPC. - - Describes a specific - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource. - - Returns: - Callable[[~.GetAzureClusterRequest], - Awaitable[~.AzureCluster]]: - 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_azure_cluster' not in self._stubs: - self._stubs['get_azure_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureCluster', - request_serializer=azure_service.GetAzureClusterRequest.serialize, - response_deserializer=azure_resources.AzureCluster.deserialize, - ) - return self._stubs['get_azure_cluster'] - - @property - def list_azure_clusters(self) -> Callable[ - [azure_service.ListAzureClustersRequest], - Awaitable[azure_service.ListAzureClustersResponse]]: - r"""Return a callable for the list azure clusters method over gRPC. - - Lists all - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resources on a given Google Cloud project and region. - - Returns: - Callable[[~.ListAzureClustersRequest], - Awaitable[~.ListAzureClustersResponse]]: - 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_azure_clusters' not in self._stubs: - self._stubs['list_azure_clusters'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureClusters', - request_serializer=azure_service.ListAzureClustersRequest.serialize, - response_deserializer=azure_service.ListAzureClustersResponse.deserialize, - ) - return self._stubs['list_azure_clusters'] - - @property - def delete_azure_cluster(self) -> Callable[ - [azure_service.DeleteAzureClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete azure cluster method over gRPC. - - Deletes a specific - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource. - - Fails if the cluster has one or more associated - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAzureClusterRequest], - 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_azure_cluster' not in self._stubs: - self._stubs['delete_azure_cluster'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureCluster', - request_serializer=azure_service.DeleteAzureClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_azure_cluster'] - - @property - def generate_azure_cluster_agent_token(self) -> Callable[ - [azure_service.GenerateAzureClusterAgentTokenRequest], - Awaitable[azure_service.GenerateAzureClusterAgentTokenResponse]]: - r"""Return a callable for the generate azure cluster agent - token method over gRPC. - - Generates an access token for a cluster agent. - - Returns: - Callable[[~.GenerateAzureClusterAgentTokenRequest], - Awaitable[~.GenerateAzureClusterAgentTokenResponse]]: - 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_azure_cluster_agent_token' not in self._stubs: - self._stubs['generate_azure_cluster_agent_token'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GenerateAzureClusterAgentToken', - request_serializer=azure_service.GenerateAzureClusterAgentTokenRequest.serialize, - response_deserializer=azure_service.GenerateAzureClusterAgentTokenResponse.deserialize, - ) - return self._stubs['generate_azure_cluster_agent_token'] - - @property - def generate_azure_access_token(self) -> Callable[ - [azure_service.GenerateAzureAccessTokenRequest], - Awaitable[azure_service.GenerateAzureAccessTokenResponse]]: - r"""Return a callable for the generate azure access token method over gRPC. - - Generates a short-lived access token to authenticate to a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource. - - Returns: - Callable[[~.GenerateAzureAccessTokenRequest], - Awaitable[~.GenerateAzureAccessTokenResponse]]: - 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_azure_access_token' not in self._stubs: - self._stubs['generate_azure_access_token'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GenerateAzureAccessToken', - request_serializer=azure_service.GenerateAzureAccessTokenRequest.serialize, - response_deserializer=azure_service.GenerateAzureAccessTokenResponse.deserialize, - ) - return self._stubs['generate_azure_access_token'] - - @property - def create_azure_node_pool(self) -> Callable[ - [azure_service.CreateAzureNodePoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create azure node pool method over gRPC. - - Creates a new - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool], - attached to a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.CreateAzureNodePoolRequest], - 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_azure_node_pool' not in self._stubs: - self._stubs['create_azure_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureNodePool', - request_serializer=azure_service.CreateAzureNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_azure_node_pool'] - - @property - def update_azure_node_pool(self) -> Callable[ - [azure_service.UpdateAzureNodePoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update azure node pool method over gRPC. - - Updates an - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. - - Returns: - Callable[[~.UpdateAzureNodePoolRequest], - 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_azure_node_pool' not in self._stubs: - self._stubs['update_azure_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/UpdateAzureNodePool', - request_serializer=azure_service.UpdateAzureNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_azure_node_pool'] - - @property - def get_azure_node_pool(self) -> Callable[ - [azure_service.GetAzureNodePoolRequest], - Awaitable[azure_resources.AzureNodePool]]: - r"""Return a callable for the get azure node pool method over gRPC. - - Describes a specific - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource. - - Returns: - Callable[[~.GetAzureNodePoolRequest], - Awaitable[~.AzureNodePool]]: - 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_azure_node_pool' not in self._stubs: - self._stubs['get_azure_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureNodePool', - request_serializer=azure_service.GetAzureNodePoolRequest.serialize, - response_deserializer=azure_resources.AzureNodePool.deserialize, - ) - return self._stubs['get_azure_node_pool'] - - @property - def list_azure_node_pools(self) -> Callable[ - [azure_service.ListAzureNodePoolsRequest], - Awaitable[azure_service.ListAzureNodePoolsResponse]]: - r"""Return a callable for the list azure node pools method over gRPC. - - Lists all - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources on a given - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - Returns: - Callable[[~.ListAzureNodePoolsRequest], - Awaitable[~.ListAzureNodePoolsResponse]]: - 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_azure_node_pools' not in self._stubs: - self._stubs['list_azure_node_pools'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureNodePools', - request_serializer=azure_service.ListAzureNodePoolsRequest.serialize, - response_deserializer=azure_service.ListAzureNodePoolsResponse.deserialize, - ) - return self._stubs['list_azure_node_pools'] - - @property - def delete_azure_node_pool(self) -> Callable[ - [azure_service.DeleteAzureNodePoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete azure node pool method over gRPC. - - Deletes a specific - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource. - - If successful, the response contains a newly created - [Operation][google.longrunning.Operation] resource that can be - described to track the status of the operation. - - Returns: - Callable[[~.DeleteAzureNodePoolRequest], - 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_azure_node_pool' not in self._stubs: - self._stubs['delete_azure_node_pool'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureNodePool', - request_serializer=azure_service.DeleteAzureNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_azure_node_pool'] - - @property - def get_azure_open_id_config(self) -> Callable[ - [azure_service.GetAzureOpenIdConfigRequest], - Awaitable[azure_resources.AzureOpenIdConfig]]: - r"""Return a callable for the get azure open id config method over gRPC. - - Gets the OIDC discovery document for the cluster. See the - `OpenID Connect Discovery 1.0 - specification `__ - for details. - - Returns: - Callable[[~.GetAzureOpenIdConfigRequest], - Awaitable[~.AzureOpenIdConfig]]: - 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_azure_open_id_config' not in self._stubs: - self._stubs['get_azure_open_id_config'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureOpenIdConfig', - request_serializer=azure_service.GetAzureOpenIdConfigRequest.serialize, - response_deserializer=azure_resources.AzureOpenIdConfig.deserialize, - ) - return self._stubs['get_azure_open_id_config'] - - @property - def get_azure_json_web_keys(self) -> Callable[ - [azure_service.GetAzureJsonWebKeysRequest], - Awaitable[azure_resources.AzureJsonWebKeys]]: - r"""Return a callable for the get azure json web keys method over gRPC. - - Gets the public component of the cluster signing keys - in JSON Web Key format. - - Returns: - Callable[[~.GetAzureJsonWebKeysRequest], - Awaitable[~.AzureJsonWebKeys]]: - 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_azure_json_web_keys' not in self._stubs: - self._stubs['get_azure_json_web_keys'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureJsonWebKeys', - request_serializer=azure_service.GetAzureJsonWebKeysRequest.serialize, - response_deserializer=azure_resources.AzureJsonWebKeys.deserialize, - ) - return self._stubs['get_azure_json_web_keys'] - - @property - def get_azure_server_config(self) -> Callable[ - [azure_service.GetAzureServerConfigRequest], - Awaitable[azure_resources.AzureServerConfig]]: - r"""Return a callable for the get azure server config method over gRPC. - - Returns information, such as supported Azure regions - and Kubernetes versions, on a given Google Cloud - location. - - Returns: - Callable[[~.GetAzureServerConfigRequest], - Awaitable[~.AzureServerConfig]]: - 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_azure_server_config' not in self._stubs: - self._stubs['get_azure_server_config'] = self._logged_channel.unary_unary( - '/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureServerConfig', - request_serializer=azure_service.GetAzureServerConfigRequest.serialize, - response_deserializer=azure_resources.AzureServerConfig.deserialize, - ) - return self._stubs['get_azure_server_config'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.create_azure_client: self._wrap_method( - self.create_azure_client, - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_client: self._wrap_method( - self.get_azure_client, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_azure_clients: self._wrap_method( - self.list_azure_clients, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_azure_client: self._wrap_method( - self.delete_azure_client, - default_timeout=60.0, - client_info=client_info, - ), - self.create_azure_cluster: self._wrap_method( - self.create_azure_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_azure_cluster: self._wrap_method( - self.update_azure_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_cluster: self._wrap_method( - self.get_azure_cluster, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_azure_clusters: self._wrap_method( - self.list_azure_clusters, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_azure_cluster: self._wrap_method( - self.delete_azure_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_azure_cluster_agent_token: self._wrap_method( - self.generate_azure_cluster_agent_token, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_azure_access_token: self._wrap_method( - self.generate_azure_access_token, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_azure_node_pool: self._wrap_method( - self.create_azure_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.update_azure_node_pool: self._wrap_method( - self.update_azure_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_node_pool: self._wrap_method( - self.get_azure_node_pool, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_azure_node_pools: self._wrap_method( - self.list_azure_node_pools, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_azure_node_pool: self._wrap_method( - self.delete_azure_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_open_id_config: self._wrap_method( - self.get_azure_open_id_config, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_json_web_keys: self._wrap_method( - self.get_azure_json_web_keys, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_azure_server_config: self._wrap_method( - self.get_azure_server_config, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @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._logged_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._logged_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._logged_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._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'AzureClustersGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest.py deleted file mode 100644 index 7e585427e148..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest.py +++ /dev/null @@ -1,3678 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # 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 gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.gke_multicloud_v1.types import azure_resources -from google.cloud.gke_multicloud_v1.types import azure_service -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseAzureClustersRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class AzureClustersRestInterceptor: - """Interceptor for AzureClusters. - - 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 AzureClustersRestTransport. - - .. code-block:: python - class MyCustomAzureClustersInterceptor(AzureClustersRestInterceptor): - def pre_create_azure_client(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_azure_client(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_azure_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_azure_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_azure_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_azure_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_azure_client(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_azure_client(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_azure_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_azure_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_azure_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_azure_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_azure_access_token(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_azure_access_token(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_azure_cluster_agent_token(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_azure_cluster_agent_token(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_azure_client(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_azure_client(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_azure_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_azure_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_azure_json_web_keys(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_azure_json_web_keys(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_azure_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_azure_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_azure_open_id_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_azure_open_id_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_azure_server_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_azure_server_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_azure_clients(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_azure_clients(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_azure_clusters(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_azure_clusters(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_azure_node_pools(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_azure_node_pools(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_azure_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_azure_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_azure_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_azure_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AzureClustersRestTransport(interceptor=MyCustomAzureClustersInterceptor()) - client = AzureClustersClient(transport=transport) - - - """ - def pre_create_azure_client(self, request: azure_service.CreateAzureClientRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.CreateAzureClientRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_azure_client - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_create_azure_client(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_azure_client - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_create_azure_cluster(self, request: azure_service.CreateAzureClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.CreateAzureClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_azure_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_create_azure_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_azure_cluster - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_create_azure_node_pool(self, request: azure_service.CreateAzureNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.CreateAzureNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_azure_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_create_azure_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_azure_node_pool - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_delete_azure_client(self, request: azure_service.DeleteAzureClientRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.DeleteAzureClientRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_azure_client - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_delete_azure_client(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_azure_client - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_delete_azure_cluster(self, request: azure_service.DeleteAzureClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.DeleteAzureClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_azure_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_delete_azure_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_azure_cluster - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_delete_azure_node_pool(self, request: azure_service.DeleteAzureNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.DeleteAzureNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_azure_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_delete_azure_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_azure_node_pool - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_generate_azure_access_token(self, request: azure_service.GenerateAzureAccessTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GenerateAzureAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for generate_azure_access_token - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_generate_azure_access_token(self, response: azure_service.GenerateAzureAccessTokenResponse) -> azure_service.GenerateAzureAccessTokenResponse: - """Post-rpc interceptor for generate_azure_access_token - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_generate_azure_cluster_agent_token(self, request: azure_service.GenerateAzureClusterAgentTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GenerateAzureClusterAgentTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for generate_azure_cluster_agent_token - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_generate_azure_cluster_agent_token(self, response: azure_service.GenerateAzureClusterAgentTokenResponse) -> azure_service.GenerateAzureClusterAgentTokenResponse: - """Post-rpc interceptor for generate_azure_cluster_agent_token - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_get_azure_client(self, request: azure_service.GetAzureClientRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureClientRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_azure_client - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_get_azure_client(self, response: azure_resources.AzureClient) -> azure_resources.AzureClient: - """Post-rpc interceptor for get_azure_client - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_get_azure_cluster(self, request: azure_service.GetAzureClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_azure_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_get_azure_cluster(self, response: azure_resources.AzureCluster) -> azure_resources.AzureCluster: - """Post-rpc interceptor for get_azure_cluster - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_get_azure_json_web_keys(self, request: azure_service.GetAzureJsonWebKeysRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureJsonWebKeysRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_azure_json_web_keys - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_get_azure_json_web_keys(self, response: azure_resources.AzureJsonWebKeys) -> azure_resources.AzureJsonWebKeys: - """Post-rpc interceptor for get_azure_json_web_keys - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_get_azure_node_pool(self, request: azure_service.GetAzureNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_azure_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_get_azure_node_pool(self, response: azure_resources.AzureNodePool) -> azure_resources.AzureNodePool: - """Post-rpc interceptor for get_azure_node_pool - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_get_azure_open_id_config(self, request: azure_service.GetAzureOpenIdConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureOpenIdConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_azure_open_id_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_get_azure_open_id_config(self, response: azure_resources.AzureOpenIdConfig) -> azure_resources.AzureOpenIdConfig: - """Post-rpc interceptor for get_azure_open_id_config - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_get_azure_server_config(self, request: azure_service.GetAzureServerConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.GetAzureServerConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_azure_server_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_get_azure_server_config(self, response: azure_resources.AzureServerConfig) -> azure_resources.AzureServerConfig: - """Post-rpc interceptor for get_azure_server_config - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_list_azure_clients(self, request: azure_service.ListAzureClientsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.ListAzureClientsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_azure_clients - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_list_azure_clients(self, response: azure_service.ListAzureClientsResponse) -> azure_service.ListAzureClientsResponse: - """Post-rpc interceptor for list_azure_clients - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_list_azure_clusters(self, request: azure_service.ListAzureClustersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.ListAzureClustersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_azure_clusters - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_list_azure_clusters(self, response: azure_service.ListAzureClustersResponse) -> azure_service.ListAzureClustersResponse: - """Post-rpc interceptor for list_azure_clusters - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_list_azure_node_pools(self, request: azure_service.ListAzureNodePoolsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.ListAzureNodePoolsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_azure_node_pools - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_list_azure_node_pools(self, response: azure_service.ListAzureNodePoolsResponse) -> azure_service.ListAzureNodePoolsResponse: - """Post-rpc interceptor for list_azure_node_pools - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_update_azure_cluster(self, request: azure_service.UpdateAzureClusterRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.UpdateAzureClusterRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_azure_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_update_azure_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_azure_cluster - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_update_azure_node_pool(self, request: azure_service.UpdateAzureNodePoolRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[azure_service.UpdateAzureNodePoolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_azure_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters server. - """ - return request, metadata - - def post_update_azure_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_azure_node_pool - - Override in a subclass to manipulate the response - after it is returned by the AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters 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 AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters 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 AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters 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 AzureClusters server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the AzureClusters 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 AzureClusters server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AzureClustersRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AzureClustersRestInterceptor - - -class AzureClustersRestTransport(_BaseAzureClustersRestTransport): - """REST backend synchronous transport for AzureClusters. - - The AzureClusters API provides a single centrally managed - service to create and manage Anthos clusters that run on Azure - infrastructure. - - 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 = 'gkemulticloud.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[AzureClustersRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - 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 AzureClustersRestInterceptor() - 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 _CreateAzureClient(_BaseAzureClustersRestTransport._BaseCreateAzureClient, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.CreateAzureClient") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: azure_service.CreateAzureClientRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create azure client method over HTTP. - - Args: - request (~.azure_service.CreateAzureClientRequest): - The request object. Request message for ``AzureClusters.CreateAzureClient`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseCreateAzureClient._get_http_options() - - request, metadata = self._interceptor.pre_create_azure_client(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseCreateAzureClient._get_transcoded_request(http_options, request) - - body = _BaseAzureClustersRestTransport._BaseCreateAzureClient._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseCreateAzureClient._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.CreateAzureClient", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "CreateAzureClient", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._CreateAzureClient._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_azure_client(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.create_azure_client", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "CreateAzureClient", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateAzureCluster(_BaseAzureClustersRestTransport._BaseCreateAzureCluster, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.CreateAzureCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: azure_service.CreateAzureClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create azure cluster method over HTTP. - - Args: - request (~.azure_service.CreateAzureClusterRequest): - The request object. Request message for ``AzureClusters.CreateAzureCluster`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseCreateAzureCluster._get_http_options() - - request, metadata = self._interceptor.pre_create_azure_cluster(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseCreateAzureCluster._get_transcoded_request(http_options, request) - - body = _BaseAzureClustersRestTransport._BaseCreateAzureCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseCreateAzureCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.CreateAzureCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "CreateAzureCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._CreateAzureCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_azure_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.create_azure_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "CreateAzureCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateAzureNodePool(_BaseAzureClustersRestTransport._BaseCreateAzureNodePool, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.CreateAzureNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: azure_service.CreateAzureNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create azure node pool method over HTTP. - - Args: - request (~.azure_service.CreateAzureNodePoolRequest): - The request object. Response message for - ``AzureClusters.CreateAzureNodePool`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseCreateAzureNodePool._get_http_options() - - request, metadata = self._interceptor.pre_create_azure_node_pool(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseCreateAzureNodePool._get_transcoded_request(http_options, request) - - body = _BaseAzureClustersRestTransport._BaseCreateAzureNodePool._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseCreateAzureNodePool._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.CreateAzureNodePool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "CreateAzureNodePool", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._CreateAzureNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_azure_node_pool(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.create_azure_node_pool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "CreateAzureNodePool", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteAzureClient(_BaseAzureClustersRestTransport._BaseDeleteAzureClient, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.DeleteAzureClient") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.DeleteAzureClientRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete azure client method over HTTP. - - Args: - request (~.azure_service.DeleteAzureClientRequest): - The request object. Request message for ``AzureClusters.DeleteAzureClient`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseDeleteAzureClient._get_http_options() - - request, metadata = self._interceptor.pre_delete_azure_client(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseDeleteAzureClient._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseDeleteAzureClient._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.DeleteAzureClient", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "DeleteAzureClient", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._DeleteAzureClient._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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_azure_client(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.delete_azure_client", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "DeleteAzureClient", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteAzureCluster(_BaseAzureClustersRestTransport._BaseDeleteAzureCluster, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.DeleteAzureCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.DeleteAzureClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete azure cluster method over HTTP. - - Args: - request (~.azure_service.DeleteAzureClusterRequest): - The request object. Request message for ``AzureClusters.DeleteAzureCluster`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseDeleteAzureCluster._get_http_options() - - request, metadata = self._interceptor.pre_delete_azure_cluster(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseDeleteAzureCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseDeleteAzureCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.DeleteAzureCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "DeleteAzureCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._DeleteAzureCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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_azure_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.delete_azure_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "DeleteAzureCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteAzureNodePool(_BaseAzureClustersRestTransport._BaseDeleteAzureNodePool, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.DeleteAzureNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.DeleteAzureNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete azure node pool method over HTTP. - - Args: - request (~.azure_service.DeleteAzureNodePoolRequest): - The request object. Request message for - ``AzureClusters.DeleteAzureNodePool`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseDeleteAzureNodePool._get_http_options() - - request, metadata = self._interceptor.pre_delete_azure_node_pool(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseDeleteAzureNodePool._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseDeleteAzureNodePool._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.DeleteAzureNodePool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "DeleteAzureNodePool", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._DeleteAzureNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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_azure_node_pool(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.delete_azure_node_pool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "DeleteAzureNodePool", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GenerateAzureAccessToken(_BaseAzureClustersRestTransport._BaseGenerateAzureAccessToken, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.GenerateAzureAccessToken") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.GenerateAzureAccessTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_service.GenerateAzureAccessTokenResponse: - r"""Call the generate azure access - token method over HTTP. - - Args: - request (~.azure_service.GenerateAzureAccessTokenRequest): - The request object. Request message for - ``AzureClusters.GenerateAzureAccessToken`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_service.GenerateAzureAccessTokenResponse: - Response message for - ``AzureClusters.GenerateAzureAccessToken`` method. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseGenerateAzureAccessToken._get_http_options() - - request, metadata = self._interceptor.pre_generate_azure_access_token(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseGenerateAzureAccessToken._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseGenerateAzureAccessToken._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GenerateAzureAccessToken", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GenerateAzureAccessToken", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._GenerateAzureAccessToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = azure_service.GenerateAzureAccessTokenResponse() - pb_resp = azure_service.GenerateAzureAccessTokenResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_generate_azure_access_token(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_service.GenerateAzureAccessTokenResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.generate_azure_access_token", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GenerateAzureAccessToken", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GenerateAzureClusterAgentToken(_BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.GenerateAzureClusterAgentToken") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: azure_service.GenerateAzureClusterAgentTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_service.GenerateAzureClusterAgentTokenResponse: - r"""Call the generate azure cluster - agent token method over HTTP. - - Args: - request (~.azure_service.GenerateAzureClusterAgentTokenRequest): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_service.GenerateAzureClusterAgentTokenResponse: - - """ - - http_options = _BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken._get_http_options() - - request, metadata = self._interceptor.pre_generate_azure_cluster_agent_token(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken._get_transcoded_request(http_options, request) - - body = _BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GenerateAzureClusterAgentToken", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GenerateAzureClusterAgentToken", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._GenerateAzureClusterAgentToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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 = azure_service.GenerateAzureClusterAgentTokenResponse() - pb_resp = azure_service.GenerateAzureClusterAgentTokenResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_generate_azure_cluster_agent_token(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_service.GenerateAzureClusterAgentTokenResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.generate_azure_cluster_agent_token", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GenerateAzureClusterAgentToken", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAzureClient(_BaseAzureClustersRestTransport._BaseGetAzureClient, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.GetAzureClient") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.GetAzureClientRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_resources.AzureClient: - r"""Call the get azure client method over HTTP. - - Args: - request (~.azure_service.GetAzureClientRequest): - The request object. Request message for ``AzureClusters.GetAzureClient`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_resources.AzureClient: - ``AzureClient`` resources hold client authentication - information needed by the Anthos Multi-Cloud API to - manage Azure resources on your Azure subscription. - - When an - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - is created, an ``AzureClient`` resource needs to be - provided and all operations on Azure resources - associated to that cluster will authenticate to Azure - services using the given client. - - ``AzureClient`` resources are immutable and cannot be - modified upon creation. - - Each ``AzureClient`` resource is bound to a single Azure - Active Directory Application and tenant. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseGetAzureClient._get_http_options() - - request, metadata = self._interceptor.pre_get_azure_client(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureClient._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseGetAzureClient._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureClient", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureClient", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._GetAzureClient._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = azure_resources.AzureClient() - pb_resp = azure_resources.AzureClient.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_azure_client(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_resources.AzureClient.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_client", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureClient", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAzureCluster(_BaseAzureClustersRestTransport._BaseGetAzureCluster, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.GetAzureCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.GetAzureClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_resources.AzureCluster: - r"""Call the get azure cluster method over HTTP. - - Args: - request (~.azure_service.GetAzureClusterRequest): - The request object. Request message for ``AzureClusters.GetAzureCluster`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_resources.AzureCluster: - An Anthos cluster running on Azure. - """ - - http_options = _BaseAzureClustersRestTransport._BaseGetAzureCluster._get_http_options() - - request, metadata = self._interceptor.pre_get_azure_cluster(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseGetAzureCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._GetAzureCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = azure_resources.AzureCluster() - pb_resp = azure_resources.AzureCluster.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_azure_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_resources.AzureCluster.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAzureJsonWebKeys(_BaseAzureClustersRestTransport._BaseGetAzureJsonWebKeys, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.GetAzureJsonWebKeys") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.GetAzureJsonWebKeysRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_resources.AzureJsonWebKeys: - r"""Call the get azure json web keys method over HTTP. - - Args: - request (~.azure_service.GetAzureJsonWebKeysRequest): - The request object. GetAzureJsonWebKeysRequest gets the public component of - the keys used by the cluster to sign token requests. - This will be the jwks_uri for the discover document - returned by getOpenIDConfig. See the OpenID Connect - Discovery 1.0 specification for details. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_resources.AzureJsonWebKeys: - AzureJsonWebKeys is a valid JSON Web - Key Set as specififed in RFC 7517. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseGetAzureJsonWebKeys._get_http_options() - - request, metadata = self._interceptor.pre_get_azure_json_web_keys(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureJsonWebKeys._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseGetAzureJsonWebKeys._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureJsonWebKeys", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureJsonWebKeys", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._GetAzureJsonWebKeys._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = azure_resources.AzureJsonWebKeys() - pb_resp = azure_resources.AzureJsonWebKeys.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_azure_json_web_keys(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_resources.AzureJsonWebKeys.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_json_web_keys", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureJsonWebKeys", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAzureNodePool(_BaseAzureClustersRestTransport._BaseGetAzureNodePool, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.GetAzureNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.GetAzureNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_resources.AzureNodePool: - r"""Call the get azure node pool method over HTTP. - - Args: - request (~.azure_service.GetAzureNodePoolRequest): - The request object. Request message for ``AzureClusters.GetAzureNodePool`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_resources.AzureNodePool: - An Anthos node pool running on Azure. - """ - - http_options = _BaseAzureClustersRestTransport._BaseGetAzureNodePool._get_http_options() - - request, metadata = self._interceptor.pre_get_azure_node_pool(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureNodePool._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseGetAzureNodePool._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureNodePool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureNodePool", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._GetAzureNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = azure_resources.AzureNodePool() - pb_resp = azure_resources.AzureNodePool.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_azure_node_pool(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_resources.AzureNodePool.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_node_pool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureNodePool", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAzureOpenIdConfig(_BaseAzureClustersRestTransport._BaseGetAzureOpenIdConfig, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.GetAzureOpenIdConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.GetAzureOpenIdConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_resources.AzureOpenIdConfig: - r"""Call the get azure open id config method over HTTP. - - Args: - request (~.azure_service.GetAzureOpenIdConfigRequest): - The request object. GetAzureOpenIdConfigRequest gets the - OIDC discovery document for the cluster. - See the OpenID Connect Discovery 1.0 - specification for details. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_resources.AzureOpenIdConfig: - AzureOpenIdConfig is an OIDC - discovery document for the cluster. See - the OpenID Connect Discovery 1.0 - specification for details. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseGetAzureOpenIdConfig._get_http_options() - - request, metadata = self._interceptor.pre_get_azure_open_id_config(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureOpenIdConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseGetAzureOpenIdConfig._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureOpenIdConfig", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureOpenIdConfig", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._GetAzureOpenIdConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = azure_resources.AzureOpenIdConfig() - pb_resp = azure_resources.AzureOpenIdConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_azure_open_id_config(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_resources.AzureOpenIdConfig.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_open_id_config", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureOpenIdConfig", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAzureServerConfig(_BaseAzureClustersRestTransport._BaseGetAzureServerConfig, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.GetAzureServerConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.GetAzureServerConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_resources.AzureServerConfig: - r"""Call the get azure server config method over HTTP. - - Args: - request (~.azure_service.GetAzureServerConfigRequest): - The request object. GetAzureServerConfigRequest gets the - server config of GKE cluster on Azure. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_resources.AzureServerConfig: - AzureServerConfig contains - information about a Google Cloud - location, such as supported Azure - regions and Kubernetes versions. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseGetAzureServerConfig._get_http_options() - - request, metadata = self._interceptor.pre_get_azure_server_config(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseGetAzureServerConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseGetAzureServerConfig._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetAzureServerConfig", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureServerConfig", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._GetAzureServerConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = azure_resources.AzureServerConfig() - pb_resp = azure_resources.AzureServerConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_azure_server_config(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_resources.AzureServerConfig.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.get_azure_server_config", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetAzureServerConfig", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListAzureClients(_BaseAzureClustersRestTransport._BaseListAzureClients, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.ListAzureClients") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.ListAzureClientsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_service.ListAzureClientsResponse: - r"""Call the list azure clients method over HTTP. - - Args: - request (~.azure_service.ListAzureClientsRequest): - The request object. Request message for ``AzureClusters.ListAzureClients`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_service.ListAzureClientsResponse: - Response message for ``AzureClusters.ListAzureClients`` - method. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseListAzureClients._get_http_options() - - request, metadata = self._interceptor.pre_list_azure_clients(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseListAzureClients._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseListAzureClients._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.ListAzureClients", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "ListAzureClients", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._ListAzureClients._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = azure_service.ListAzureClientsResponse() - pb_resp = azure_service.ListAzureClientsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_azure_clients(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_service.ListAzureClientsResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.list_azure_clients", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "ListAzureClients", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListAzureClusters(_BaseAzureClustersRestTransport._BaseListAzureClusters, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.ListAzureClusters") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.ListAzureClustersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_service.ListAzureClustersResponse: - r"""Call the list azure clusters method over HTTP. - - Args: - request (~.azure_service.ListAzureClustersRequest): - The request object. Request message for ``AzureClusters.ListAzureClusters`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_service.ListAzureClustersResponse: - Response message for ``AzureClusters.ListAzureClusters`` - method. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseListAzureClusters._get_http_options() - - request, metadata = self._interceptor.pre_list_azure_clusters(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseListAzureClusters._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseListAzureClusters._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.ListAzureClusters", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "ListAzureClusters", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._ListAzureClusters._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = azure_service.ListAzureClustersResponse() - pb_resp = azure_service.ListAzureClustersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_azure_clusters(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_service.ListAzureClustersResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.list_azure_clusters", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "ListAzureClusters", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListAzureNodePools(_BaseAzureClustersRestTransport._BaseListAzureNodePools, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.ListAzureNodePools") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: azure_service.ListAzureNodePoolsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> azure_service.ListAzureNodePoolsResponse: - r"""Call the list azure node pools method over HTTP. - - Args: - request (~.azure_service.ListAzureNodePoolsRequest): - The request object. Request message for ``AzureClusters.ListAzureNodePools`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.azure_service.ListAzureNodePoolsResponse: - Response message for - ``AzureClusters.ListAzureNodePools`` method. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseListAzureNodePools._get_http_options() - - request, metadata = self._interceptor.pre_list_azure_node_pools(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseListAzureNodePools._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseListAzureNodePools._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.ListAzureNodePools", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "ListAzureNodePools", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._ListAzureNodePools._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = azure_service.ListAzureNodePoolsResponse() - pb_resp = azure_service.ListAzureNodePoolsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_azure_node_pools(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = azure_service.ListAzureNodePoolsResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.list_azure_node_pools", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "ListAzureNodePools", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateAzureCluster(_BaseAzureClustersRestTransport._BaseUpdateAzureCluster, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.UpdateAzureCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: azure_service.UpdateAzureClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update azure cluster method over HTTP. - - Args: - request (~.azure_service.UpdateAzureClusterRequest): - The request object. Request message for ``AzureClusters.UpdateAzureCluster`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseUpdateAzureCluster._get_http_options() - - request, metadata = self._interceptor.pre_update_azure_cluster(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseUpdateAzureCluster._get_transcoded_request(http_options, request) - - body = _BaseAzureClustersRestTransport._BaseUpdateAzureCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseUpdateAzureCluster._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.UpdateAzureCluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "UpdateAzureCluster", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._UpdateAzureCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_azure_cluster(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.update_azure_cluster", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "UpdateAzureCluster", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateAzureNodePool(_BaseAzureClustersRestTransport._BaseUpdateAzureNodePool, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.UpdateAzureNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: azure_service.UpdateAzureNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update azure node pool method over HTTP. - - Args: - request (~.azure_service.UpdateAzureNodePoolRequest): - The request object. Request message for - ``AzureClusters.UpdateAzureNodePool`` 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseAzureClustersRestTransport._BaseUpdateAzureNodePool._get_http_options() - - request, metadata = self._interceptor.pre_update_azure_node_pool(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseUpdateAzureNodePool._get_transcoded_request(http_options, request) - - body = _BaseAzureClustersRestTransport._BaseUpdateAzureNodePool._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseUpdateAzureNodePool._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.UpdateAzureNodePool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "UpdateAzureNodePool", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._UpdateAzureNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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_azure_node_pool(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersClient.update_azure_node_pool", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "UpdateAzureNodePool", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_azure_client(self) -> Callable[ - [azure_service.CreateAzureClientRequest], - 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._CreateAzureClient(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_azure_cluster(self) -> Callable[ - [azure_service.CreateAzureClusterRequest], - 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._CreateAzureCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_azure_node_pool(self) -> Callable[ - [azure_service.CreateAzureNodePoolRequest], - 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._CreateAzureNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_azure_client(self) -> Callable[ - [azure_service.DeleteAzureClientRequest], - 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._DeleteAzureClient(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_azure_cluster(self) -> Callable[ - [azure_service.DeleteAzureClusterRequest], - 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._DeleteAzureCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_azure_node_pool(self) -> Callable[ - [azure_service.DeleteAzureNodePoolRequest], - 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._DeleteAzureNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_azure_access_token(self) -> Callable[ - [azure_service.GenerateAzureAccessTokenRequest], - azure_service.GenerateAzureAccessTokenResponse]: - # 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._GenerateAzureAccessToken(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_azure_cluster_agent_token(self) -> Callable[ - [azure_service.GenerateAzureClusterAgentTokenRequest], - azure_service.GenerateAzureClusterAgentTokenResponse]: - # 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._GenerateAzureClusterAgentToken(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_azure_client(self) -> Callable[ - [azure_service.GetAzureClientRequest], - azure_resources.AzureClient]: - # 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._GetAzureClient(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_azure_cluster(self) -> Callable[ - [azure_service.GetAzureClusterRequest], - azure_resources.AzureCluster]: - # 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._GetAzureCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_azure_json_web_keys(self) -> Callable[ - [azure_service.GetAzureJsonWebKeysRequest], - azure_resources.AzureJsonWebKeys]: - # 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._GetAzureJsonWebKeys(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_azure_node_pool(self) -> Callable[ - [azure_service.GetAzureNodePoolRequest], - azure_resources.AzureNodePool]: - # 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._GetAzureNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_azure_open_id_config(self) -> Callable[ - [azure_service.GetAzureOpenIdConfigRequest], - azure_resources.AzureOpenIdConfig]: - # 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._GetAzureOpenIdConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_azure_server_config(self) -> Callable[ - [azure_service.GetAzureServerConfigRequest], - azure_resources.AzureServerConfig]: - # 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._GetAzureServerConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_azure_clients(self) -> Callable[ - [azure_service.ListAzureClientsRequest], - azure_service.ListAzureClientsResponse]: - # 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._ListAzureClients(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_azure_clusters(self) -> Callable[ - [azure_service.ListAzureClustersRequest], - azure_service.ListAzureClustersResponse]: - # 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._ListAzureClusters(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_azure_node_pools(self) -> Callable[ - [azure_service.ListAzureNodePoolsRequest], - azure_service.ListAzureNodePoolsResponse]: - # 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._ListAzureNodePools(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_azure_cluster(self) -> Callable[ - [azure_service.UpdateAzureClusterRequest], - 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._UpdateAzureCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_azure_node_pool(self) -> Callable[ - [azure_service.UpdateAzureNodePoolRequest], - 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._UpdateAzureNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseAzureClustersRestTransport._BaseCancelOperation, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseAzureClustersRestTransport._BaseCancelOperation._get_http_options() - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseAzureClustersRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.CancelOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "CancelOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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(_BaseAzureClustersRestTransport._BaseDeleteOperation, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseAzureClustersRestTransport._BaseDeleteOperation._get_http_options() - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.DeleteOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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(_BaseAzureClustersRestTransport._BaseGetOperation, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseAzureClustersRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.GetOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersAsyncClient.GetOperation", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "GetOperation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseAzureClustersRestTransport._BaseListOperations, AzureClustersRestStub): - def __hash__(self): - return hash("AzureClustersRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseAzureClustersRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseAzureClustersRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAzureClustersRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.gkemulticloud_v1.AzureClustersClient.ListOperations", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AzureClustersRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.gkemulticloud_v1.AzureClustersAsyncClient.ListOperations", - extra = { - "serviceName": "google.cloud.gkemulticloud.v1.AzureClusters", - "rpcName": "ListOperations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AzureClustersRestTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest_base.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest_base.py deleted file mode 100644 index bd10e183c28a..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/services/azure_clusters/transports/rest_base.py +++ /dev/null @@ -1,942 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import AzureClustersTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.gke_multicloud_v1.types import azure_resources -from google.cloud.gke_multicloud_v1.types import azure_service -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseAzureClustersRestTransport(AzureClustersTransport): - """Base REST backend transport for AzureClusters. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - 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 = 'gkemulticloud.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkemulticloud.googleapis.com'). - credentials (Optional[Any]): 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. - 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 - 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 - ) - - class _BaseCreateAzureClient: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "azureClientId" : "", } - - @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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/azureClients', - 'body': 'azure_client', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.CreateAzureClientRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseCreateAzureClient._get_unset_required_fields(query_params)) - - return query_params - - class _BaseCreateAzureCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "azureClusterId" : "", } - - @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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/azureClusters', - 'body': 'azure_cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.CreateAzureClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseCreateAzureCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseCreateAzureNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "azureNodePoolId" : "", } - - @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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/azureClusters/*}/azureNodePools', - 'body': 'azure_node_pool', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.CreateAzureNodePoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseCreateAzureNodePool._get_unset_required_fields(query_params)) - - return query_params - - class _BaseDeleteAzureClient: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/azureClients/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.DeleteAzureClientRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseDeleteAzureClient._get_unset_required_fields(query_params)) - - return query_params - - class _BaseDeleteAzureCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/azureClusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.DeleteAzureClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseDeleteAzureCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseDeleteAzureNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/azureClusters/*/azureNodePools/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.DeleteAzureNodePoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseDeleteAzureNodePool._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGenerateAzureAccessToken: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{azure_cluster=projects/*/locations/*/azureClusters/*}:generateAzureAccessToken', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.GenerateAzureAccessTokenRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseGenerateAzureAccessToken._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGenerateAzureClusterAgentToken: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{azure_cluster=projects/*/locations/*/azureClusters/*}:generateAzureClusterAgentToken', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.GenerateAzureClusterAgentTokenRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseGenerateAzureClusterAgentToken._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAzureClient: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/azureClients/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.GetAzureClientRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureClient._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAzureCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/azureClusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.GetAzureClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAzureJsonWebKeys: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{azure_cluster=projects/*/locations/*/azureClusters/*}/jwks', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.GetAzureJsonWebKeysRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureJsonWebKeys._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAzureNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/azureClusters/*/azureNodePools/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.GetAzureNodePoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureNodePool._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAzureOpenIdConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{azure_cluster=projects/*/locations/*/azureClusters/*}/.well-known/openid-configuration', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.GetAzureOpenIdConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureOpenIdConfig._get_unset_required_fields(query_params)) - - return query_params - - class _BaseGetAzureServerConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/azureServerConfig}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.GetAzureServerConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseGetAzureServerConfig._get_unset_required_fields(query_params)) - - return query_params - - class _BaseListAzureClients: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/azureClients', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.ListAzureClientsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseListAzureClients._get_unset_required_fields(query_params)) - - return query_params - - class _BaseListAzureClusters: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/azureClusters', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.ListAzureClustersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseListAzureClusters._get_unset_required_fields(query_params)) - - return query_params - - class _BaseListAzureNodePools: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/azureClusters/*}/azureNodePools', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.ListAzureNodePoolsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseListAzureNodePools._get_unset_required_fields(query_params)) - - return query_params - - class _BaseUpdateAzureCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{azure_cluster.name=projects/*/locations/*/azureClusters/*}', - 'body': 'azure_cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.UpdateAzureClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseUpdateAzureCluster._get_unset_required_fields(query_params)) - - return query_params - - class _BaseUpdateAzureNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{azure_node_pool.name=projects/*/locations/*/azureClusters/*/azureNodePools/*}', - 'body': 'azure_node_pool', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = azure_service.UpdateAzureNodePoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseAzureClustersRestTransport._BaseUpdateAzureNodePool._get_unset_required_fields(query_params)) - - return query_params - - class _BaseCancelOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseDeleteOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListOperations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseAzureClustersRestTransport', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/__init__.py deleted file mode 100644 index 8d04ddebf177..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/__init__.py +++ /dev/null @@ -1,296 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .attached_resources import ( - AttachedCluster, - AttachedClusterError, - AttachedClusterGroup, - AttachedClustersAuthorization, - AttachedClusterUser, - AttachedOidcConfig, - AttachedPlatformVersionInfo, - AttachedProxyConfig, - AttachedServerConfig, - KubernetesSecret, -) -from .attached_service import ( - CreateAttachedClusterRequest, - DeleteAttachedClusterRequest, - GenerateAttachedClusterAgentTokenRequest, - GenerateAttachedClusterAgentTokenResponse, - GenerateAttachedClusterInstallManifestRequest, - GenerateAttachedClusterInstallManifestResponse, - GetAttachedClusterRequest, - GetAttachedServerConfigRequest, - ImportAttachedClusterRequest, - ListAttachedClustersRequest, - ListAttachedClustersResponse, - UpdateAttachedClusterRequest, -) -from .aws_resources import ( - AwsAuthorization, - AwsAutoscalingGroupMetricsCollection, - AwsCluster, - AwsClusterError, - AwsClusterGroup, - AwsClusterNetworking, - AwsClusterUser, - AwsConfigEncryption, - AwsControlPlane, - AwsDatabaseEncryption, - AwsInstancePlacement, - AwsJsonWebKeys, - AwsK8sVersionInfo, - AwsNodeConfig, - AwsNodeManagement, - AwsNodePool, - AwsNodePoolAutoscaling, - AwsNodePoolError, - AwsOpenIdConfig, - AwsProxyConfig, - AwsServerConfig, - AwsServicesAuthentication, - AwsSshConfig, - AwsVolumeTemplate, - SpotConfig, - SurgeSettings, - UpdateSettings, -) -from .aws_service import ( - CreateAwsClusterRequest, - CreateAwsNodePoolRequest, - DeleteAwsClusterRequest, - DeleteAwsNodePoolRequest, - GenerateAwsAccessTokenRequest, - GenerateAwsAccessTokenResponse, - GenerateAwsClusterAgentTokenRequest, - GenerateAwsClusterAgentTokenResponse, - GetAwsClusterRequest, - GetAwsJsonWebKeysRequest, - GetAwsNodePoolRequest, - GetAwsOpenIdConfigRequest, - GetAwsServerConfigRequest, - ListAwsClustersRequest, - ListAwsClustersResponse, - ListAwsNodePoolsRequest, - ListAwsNodePoolsResponse, - RollbackAwsNodePoolUpdateRequest, - UpdateAwsClusterRequest, - UpdateAwsNodePoolRequest, -) -from .azure_resources import ( - AzureAuthorization, - AzureClient, - AzureCluster, - AzureClusterError, - AzureClusterGroup, - AzureClusterNetworking, - AzureClusterResources, - AzureClusterUser, - AzureConfigEncryption, - AzureControlPlane, - AzureDatabaseEncryption, - AzureDiskTemplate, - AzureJsonWebKeys, - AzureK8sVersionInfo, - AzureNodeConfig, - AzureNodeManagement, - AzureNodePool, - AzureNodePoolAutoscaling, - AzureNodePoolError, - AzureOpenIdConfig, - AzureProxyConfig, - AzureServerConfig, - AzureServicesAuthentication, - AzureSshConfig, - ReplicaPlacement, -) -from .azure_service import ( - CreateAzureClientRequest, - CreateAzureClusterRequest, - CreateAzureNodePoolRequest, - DeleteAzureClientRequest, - DeleteAzureClusterRequest, - DeleteAzureNodePoolRequest, - GenerateAzureAccessTokenRequest, - GenerateAzureAccessTokenResponse, - GenerateAzureClusterAgentTokenRequest, - GenerateAzureClusterAgentTokenResponse, - GetAzureClientRequest, - GetAzureClusterRequest, - GetAzureJsonWebKeysRequest, - GetAzureNodePoolRequest, - GetAzureOpenIdConfigRequest, - GetAzureServerConfigRequest, - ListAzureClientsRequest, - ListAzureClientsResponse, - ListAzureClustersRequest, - ListAzureClustersResponse, - ListAzureNodePoolsRequest, - ListAzureNodePoolsResponse, - UpdateAzureClusterRequest, - UpdateAzureNodePoolRequest, -) -from .common_resources import ( - BinaryAuthorization, - CloudMonitoringConfig, - Fleet, - Jwk, - LoggingComponentConfig, - LoggingConfig, - ManagedPrometheusConfig, - MaxPodsConstraint, - MonitoringConfig, - NodeKubeletConfig, - NodeTaint, - OperationMetadata, - SecurityPostureConfig, - WorkloadIdentityConfig, -) - -__all__ = ( - 'AttachedCluster', - 'AttachedClusterError', - 'AttachedClusterGroup', - 'AttachedClustersAuthorization', - 'AttachedClusterUser', - 'AttachedOidcConfig', - 'AttachedPlatformVersionInfo', - 'AttachedProxyConfig', - 'AttachedServerConfig', - 'KubernetesSecret', - 'CreateAttachedClusterRequest', - 'DeleteAttachedClusterRequest', - 'GenerateAttachedClusterAgentTokenRequest', - 'GenerateAttachedClusterAgentTokenResponse', - 'GenerateAttachedClusterInstallManifestRequest', - 'GenerateAttachedClusterInstallManifestResponse', - 'GetAttachedClusterRequest', - 'GetAttachedServerConfigRequest', - 'ImportAttachedClusterRequest', - 'ListAttachedClustersRequest', - 'ListAttachedClustersResponse', - 'UpdateAttachedClusterRequest', - 'AwsAuthorization', - 'AwsAutoscalingGroupMetricsCollection', - 'AwsCluster', - 'AwsClusterError', - 'AwsClusterGroup', - 'AwsClusterNetworking', - 'AwsClusterUser', - 'AwsConfigEncryption', - 'AwsControlPlane', - 'AwsDatabaseEncryption', - 'AwsInstancePlacement', - 'AwsJsonWebKeys', - 'AwsK8sVersionInfo', - 'AwsNodeConfig', - 'AwsNodeManagement', - 'AwsNodePool', - 'AwsNodePoolAutoscaling', - 'AwsNodePoolError', - 'AwsOpenIdConfig', - 'AwsProxyConfig', - 'AwsServerConfig', - 'AwsServicesAuthentication', - 'AwsSshConfig', - 'AwsVolumeTemplate', - 'SpotConfig', - 'SurgeSettings', - 'UpdateSettings', - 'CreateAwsClusterRequest', - 'CreateAwsNodePoolRequest', - 'DeleteAwsClusterRequest', - 'DeleteAwsNodePoolRequest', - 'GenerateAwsAccessTokenRequest', - 'GenerateAwsAccessTokenResponse', - 'GenerateAwsClusterAgentTokenRequest', - 'GenerateAwsClusterAgentTokenResponse', - 'GetAwsClusterRequest', - 'GetAwsJsonWebKeysRequest', - 'GetAwsNodePoolRequest', - 'GetAwsOpenIdConfigRequest', - 'GetAwsServerConfigRequest', - 'ListAwsClustersRequest', - 'ListAwsClustersResponse', - 'ListAwsNodePoolsRequest', - 'ListAwsNodePoolsResponse', - 'RollbackAwsNodePoolUpdateRequest', - 'UpdateAwsClusterRequest', - 'UpdateAwsNodePoolRequest', - 'AzureAuthorization', - 'AzureClient', - 'AzureCluster', - 'AzureClusterError', - 'AzureClusterGroup', - 'AzureClusterNetworking', - 'AzureClusterResources', - 'AzureClusterUser', - 'AzureConfigEncryption', - 'AzureControlPlane', - 'AzureDatabaseEncryption', - 'AzureDiskTemplate', - 'AzureJsonWebKeys', - 'AzureK8sVersionInfo', - 'AzureNodeConfig', - 'AzureNodeManagement', - 'AzureNodePool', - 'AzureNodePoolAutoscaling', - 'AzureNodePoolError', - 'AzureOpenIdConfig', - 'AzureProxyConfig', - 'AzureServerConfig', - 'AzureServicesAuthentication', - 'AzureSshConfig', - 'ReplicaPlacement', - 'CreateAzureClientRequest', - 'CreateAzureClusterRequest', - 'CreateAzureNodePoolRequest', - 'DeleteAzureClientRequest', - 'DeleteAzureClusterRequest', - 'DeleteAzureNodePoolRequest', - 'GenerateAzureAccessTokenRequest', - 'GenerateAzureAccessTokenResponse', - 'GenerateAzureClusterAgentTokenRequest', - 'GenerateAzureClusterAgentTokenResponse', - 'GetAzureClientRequest', - 'GetAzureClusterRequest', - 'GetAzureJsonWebKeysRequest', - 'GetAzureNodePoolRequest', - 'GetAzureOpenIdConfigRequest', - 'GetAzureServerConfigRequest', - 'ListAzureClientsRequest', - 'ListAzureClientsResponse', - 'ListAzureClustersRequest', - 'ListAzureClustersResponse', - 'ListAzureNodePoolsRequest', - 'ListAzureNodePoolsResponse', - 'UpdateAzureClusterRequest', - 'UpdateAzureNodePoolRequest', - 'BinaryAuthorization', - 'CloudMonitoringConfig', - 'Fleet', - 'Jwk', - 'LoggingComponentConfig', - 'LoggingConfig', - 'ManagedPrometheusConfig', - 'MaxPodsConstraint', - 'MonitoringConfig', - 'NodeKubeletConfig', - 'NodeTaint', - 'OperationMetadata', - 'SecurityPostureConfig', - 'WorkloadIdentityConfig', -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_resources.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_resources.py deleted file mode 100644 index b649356e5627..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_resources.py +++ /dev/null @@ -1,505 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.gke_multicloud_v1.types import common_resources -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.gkemulticloud.v1', - manifest={ - 'AttachedCluster', - 'AttachedClustersAuthorization', - 'AttachedClusterUser', - 'AttachedClusterGroup', - 'AttachedOidcConfig', - 'AttachedServerConfig', - 'AttachedPlatformVersionInfo', - 'AttachedClusterError', - 'AttachedProxyConfig', - 'KubernetesSecret', - }, -) - - -class AttachedCluster(proto.Message): - r"""An Anthos cluster running on customer own infrastructure. - - Attributes: - name (str): - The name of this resource. - - Cluster names are formatted as - ``projects//locations//attachedClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - description (str): - Optional. A human readable description of - this cluster. Cannot be longer than 255 UTF-8 - encoded bytes. - oidc_config (google.cloud.gke_multicloud_v1.types.AttachedOidcConfig): - Required. OpenID Connect (OIDC) configuration - for the cluster. - platform_version (str): - Required. The platform version for the cluster (e.g. - ``1.19.0-gke.1000``). - - You can list all supported versions on a given Google Cloud - region by calling - [GetAttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedServerConfig]. - distribution (str): - Required. The Kubernetes distribution of the underlying - attached cluster. - - Supported values: ["eks", "aks", "generic"]. - cluster_region (str): - Output only. The region where this cluster - runs. - For EKS clusters, this is a AWS region. For AKS - clusters, this is an Azure region. - fleet (google.cloud.gke_multicloud_v1.types.Fleet): - Required. Fleet configuration. - state (google.cloud.gke_multicloud_v1.types.AttachedCluster.State): - Output only. The current state of the - cluster. - uid (str): - Output only. A globally unique identifier for - the cluster. - reconciling (bool): - Output only. If set, there are currently - changes in flight to the cluster. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this cluster - was registered. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this cluster - was last updated. - etag (str): - Allows clients to perform consistent - read-modify-writes through optimistic - concurrency control. - - Can be sent on update and delete requests to - ensure the client has an up-to-date value before - proceeding. - kubernetes_version (str): - Output only. The Kubernetes version of the - cluster. - annotations (MutableMapping[str, str]): - Optional. Annotations on the cluster. - - This field has the same restrictions as Kubernetes - annotations. The total size of all keys and values combined - is limited to 256k. Key can have 2 segments: prefix - (optional) and name (required), separated by a slash (/). - Prefix must be a DNS subdomain. Name must be 63 characters - or less, begin and end with alphanumerics, with dashes (-), - underscores (_), dots (.), and alphanumerics between. - workload_identity_config (google.cloud.gke_multicloud_v1.types.WorkloadIdentityConfig): - Output only. Workload Identity settings. - logging_config (google.cloud.gke_multicloud_v1.types.LoggingConfig): - Optional. Logging configuration for this - cluster. - errors (MutableSequence[google.cloud.gke_multicloud_v1.types.AttachedClusterError]): - Output only. A set of errors found in the - cluster. - authorization (google.cloud.gke_multicloud_v1.types.AttachedClustersAuthorization): - Optional. Configuration related to the - cluster RBAC settings. - monitoring_config (google.cloud.gke_multicloud_v1.types.MonitoringConfig): - Optional. Monitoring configuration for this - cluster. - proxy_config (google.cloud.gke_multicloud_v1.types.AttachedProxyConfig): - Optional. Proxy configuration for outbound - HTTP(S) traffic. - binary_authorization (google.cloud.gke_multicloud_v1.types.BinaryAuthorization): - Optional. Binary Authorization configuration - for this cluster. - security_posture_config (google.cloud.gke_multicloud_v1.types.SecurityPostureConfig): - Optional. Security Posture configuration for - this cluster. - tags (MutableMapping[str, str]): - Optional. Input only. Tag keys/values directly bound to this - resource. - - Tag key must be specified in the format / where the tag - namespace is the ID of the organization or name of the - project that the tag key is defined in. The short name of a - tag key or value can have a maximum length of 256 - characters. The permitted character set for the short name - includes UTF-8 encoded Unicode characters except single - quotes ('), double quotes ("), backslashes (), and forward - slashes (/). - - See - `Tags `__ - for more details on Google Cloud Platform tags. - """ - class State(proto.Enum): - r"""The lifecycle state of the cluster. - - Values: - STATE_UNSPECIFIED (0): - Not set. - PROVISIONING (1): - The PROVISIONING state indicates the cluster - is being registered. - RUNNING (2): - The RUNNING state indicates the cluster has - been register and is fully usable. - RECONCILING (3): - The RECONCILING state indicates that some - work is actively being done on the cluster, such - as upgrading software components. - STOPPING (4): - The STOPPING state indicates the cluster is - being de-registered. - ERROR (5): - The ERROR state indicates the cluster is in a - broken unrecoverable state. - DEGRADED (6): - The DEGRADED state indicates the cluster - requires user action to restore full - functionality. - """ - STATE_UNSPECIFIED = 0 - PROVISIONING = 1 - RUNNING = 2 - RECONCILING = 3 - STOPPING = 4 - ERROR = 5 - DEGRADED = 6 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - oidc_config: 'AttachedOidcConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='AttachedOidcConfig', - ) - platform_version: str = proto.Field( - proto.STRING, - number=4, - ) - distribution: str = proto.Field( - proto.STRING, - number=16, - ) - cluster_region: str = proto.Field( - proto.STRING, - number=22, - ) - fleet: common_resources.Fleet = proto.Field( - proto.MESSAGE, - number=5, - message=common_resources.Fleet, - ) - state: State = proto.Field( - proto.ENUM, - number=6, - enum=State, - ) - uid: str = proto.Field( - proto.STRING, - number=7, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=8, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=11, - ) - kubernetes_version: str = proto.Field( - proto.STRING, - number=12, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=13, - ) - workload_identity_config: common_resources.WorkloadIdentityConfig = proto.Field( - proto.MESSAGE, - number=14, - message=common_resources.WorkloadIdentityConfig, - ) - logging_config: common_resources.LoggingConfig = proto.Field( - proto.MESSAGE, - number=15, - message=common_resources.LoggingConfig, - ) - errors: MutableSequence['AttachedClusterError'] = proto.RepeatedField( - proto.MESSAGE, - number=20, - message='AttachedClusterError', - ) - authorization: 'AttachedClustersAuthorization' = proto.Field( - proto.MESSAGE, - number=21, - message='AttachedClustersAuthorization', - ) - monitoring_config: common_resources.MonitoringConfig = proto.Field( - proto.MESSAGE, - number=23, - message=common_resources.MonitoringConfig, - ) - proxy_config: 'AttachedProxyConfig' = proto.Field( - proto.MESSAGE, - number=24, - message='AttachedProxyConfig', - ) - binary_authorization: common_resources.BinaryAuthorization = proto.Field( - proto.MESSAGE, - number=25, - message=common_resources.BinaryAuthorization, - ) - security_posture_config: common_resources.SecurityPostureConfig = proto.Field( - proto.MESSAGE, - number=26, - message=common_resources.SecurityPostureConfig, - ) - tags: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=27, - ) - - -class AttachedClustersAuthorization(proto.Message): - r"""Configuration related to the cluster RBAC settings. - - Attributes: - admin_users (MutableSequence[google.cloud.gke_multicloud_v1.types.AttachedClusterUser]): - Optional. Users that can perform operations as a cluster - admin. A managed ClusterRoleBinding will be created to grant - the ``cluster-admin`` ClusterRole to the users. Up to ten - admin users can be provided. - - For more info on RBAC, see - https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles - admin_groups (MutableSequence[google.cloud.gke_multicloud_v1.types.AttachedClusterGroup]): - Optional. Groups of users that can perform operations as a - cluster admin. A managed ClusterRoleBinding will be created - to grant the ``cluster-admin`` ClusterRole to the groups. Up - to ten admin groups can be provided. - - For more info on RBAC, see - https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles - """ - - admin_users: MutableSequence['AttachedClusterUser'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AttachedClusterUser', - ) - admin_groups: MutableSequence['AttachedClusterGroup'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AttachedClusterGroup', - ) - - -class AttachedClusterUser(proto.Message): - r"""Identities of a user-type subject for Attached clusters. - - Attributes: - username (str): - Required. The name of the user, e.g. - ``my-gcp-id@gmail.com``. - """ - - username: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AttachedClusterGroup(proto.Message): - r"""Identities of a group-type subject for Attached clusters. - - Attributes: - group (str): - Required. The name of the group, e.g. - ``my-group@domain.com``. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AttachedOidcConfig(proto.Message): - r"""OIDC discovery information of the target cluster. - - Kubernetes Service Account (KSA) tokens are JWT tokens signed by the - cluster API server. This fields indicates how Google Cloud Platform - services validate KSA tokens in order to allow system workloads - (such as GKE Connect and telemetry agents) to authenticate back to - Google Cloud Platform. - - Both clusters with public and private issuer URLs are supported. - Clusters with public issuers only need to specify the ``issuer_url`` - field while clusters with private issuers need to provide both - ``issuer_url`` and ``oidc_jwks``. - - Attributes: - issuer_url (str): - A JSON Web Token (JWT) issuer URI. ``issuer`` must start - with ``https://``. - jwks (bytes): - Optional. OIDC verification keys in JWKS - format (RFC 7517). It contains a list of OIDC - verification keys that can be used to verify - OIDC JWTs. - - This field is required for cluster that doesn't - have a publicly available discovery endpoint. - When provided, it will be directly used to - verify the OIDC JWT asserted by the IDP. - """ - - issuer_url: str = proto.Field( - proto.STRING, - number=1, - ) - jwks: bytes = proto.Field( - proto.BYTES, - number=2, - ) - - -class AttachedServerConfig(proto.Message): - r"""AttachedServerConfig provides information about supported - Kubernetes versions - - Attributes: - name (str): - The resource name of the config. - valid_versions (MutableSequence[google.cloud.gke_multicloud_v1.types.AttachedPlatformVersionInfo]): - List of valid platform versions. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - valid_versions: MutableSequence['AttachedPlatformVersionInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AttachedPlatformVersionInfo', - ) - - -class AttachedPlatformVersionInfo(proto.Message): - r"""Information about a supported Attached Clusters platform - version. - - Attributes: - version (str): - Platform version name. - """ - - version: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AttachedClusterError(proto.Message): - r"""AttachedClusterError describes errors found on attached - clusters. - - Attributes: - message (str): - Human-friendly description of the error. - """ - - message: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AttachedProxyConfig(proto.Message): - r"""Details of a proxy config. - - Attributes: - kubernetes_secret (google.cloud.gke_multicloud_v1.types.KubernetesSecret): - The Kubernetes Secret resource that contains - the HTTP(S) proxy configuration. The secret must - be a JSON encoded proxy configuration as - described in - https://cloud.google.com/kubernetes-engine/multi-cloud/docs/attached/eks/how-to/use-a-proxy#configure-proxy-support - for EKS clusters and - https://cloud.google.com/kubernetes-engine/multi-cloud/docs/attached/aks/how-to/use-a-proxy#configure-proxy-support - for AKS clusters. - """ - - kubernetes_secret: 'KubernetesSecret' = proto.Field( - proto.MESSAGE, - number=1, - message='KubernetesSecret', - ) - - -class KubernetesSecret(proto.Message): - r"""Information about a Kubernetes Secret - - Attributes: - name (str): - Name of the kubernetes secret. - namespace (str): - Namespace in which the kubernetes secret is - stored. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - namespace: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_service.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_service.py deleted file mode 100644 index c70df2d38a21..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/attached_service.py +++ /dev/null @@ -1,574 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.gke_multicloud_v1.types import attached_resources -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.gkemulticloud.v1', - manifest={ - 'GenerateAttachedClusterInstallManifestRequest', - 'GenerateAttachedClusterInstallManifestResponse', - 'CreateAttachedClusterRequest', - 'ImportAttachedClusterRequest', - 'UpdateAttachedClusterRequest', - 'GetAttachedClusterRequest', - 'ListAttachedClustersRequest', - 'ListAttachedClustersResponse', - 'DeleteAttachedClusterRequest', - 'GetAttachedServerConfigRequest', - 'GenerateAttachedClusterAgentTokenRequest', - 'GenerateAttachedClusterAgentTokenResponse', - }, -) - - -class GenerateAttachedClusterInstallManifestRequest(proto.Message): - r"""Request message for - ``AttachedClusters.GenerateAttachedClusterInstallManifest`` method. - - Attributes: - parent (str): - Required. The parent location where this - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - attached_cluster_id (str): - Required. A client provided ID of the resource. Must be - unique within the parent resource. - - The provided ID will be part of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource name formatted as - ``projects//locations//attachedClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - - When generating an install manifest for importing an - existing Membership resource, the attached_cluster_id field - must be the Membership id. - - Membership names are formatted as - ``projects//locations//memberships/``. - platform_version (str): - Required. The platform version for the cluster (e.g. - ``1.19.0-gke.1000``). - - You can list all supported versions on a given Google Cloud - region by calling - [GetAttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedServerConfig]. - proxy_config (google.cloud.gke_multicloud_v1.types.AttachedProxyConfig): - Optional. Proxy configuration for outbound - HTTP(S) traffic. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - attached_cluster_id: str = proto.Field( - proto.STRING, - number=2, - ) - platform_version: str = proto.Field( - proto.STRING, - number=3, - ) - proxy_config: attached_resources.AttachedProxyConfig = proto.Field( - proto.MESSAGE, - number=4, - message=attached_resources.AttachedProxyConfig, - ) - - -class GenerateAttachedClusterInstallManifestResponse(proto.Message): - r"""Response message for - ``AttachedClusters.GenerateAttachedClusterInstallManifest`` method. - - Attributes: - manifest (str): - A set of Kubernetes resources (in YAML - format) to be applied to the cluster to be - attached. - """ - - manifest: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateAttachedClusterRequest(proto.Message): - r"""Request message for ``AttachedClusters.CreateAttachedCluster`` - method. - - Attributes: - parent (str): - Required. The parent location where this - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - attached_cluster (google.cloud.gke_multicloud_v1.types.AttachedCluster): - Required. The specification of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - to create. - attached_cluster_id (str): - Required. A client provided ID the resource. Must be unique - within the parent resource. - - The provided ID will be part of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource name formatted as - ``projects//locations//attachedClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - validate_only (bool): - If set, only validate the request, but do not - actually create the cluster. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - attached_cluster: attached_resources.AttachedCluster = proto.Field( - proto.MESSAGE, - number=2, - message=attached_resources.AttachedCluster, - ) - attached_cluster_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class ImportAttachedClusterRequest(proto.Message): - r"""Request message for ``AttachedClusters.ImportAttachedCluster`` - method. - - Attributes: - parent (str): - Required. The parent location where this - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - validate_only (bool): - If set, only validate the request, but do not - actually import the cluster. - fleet_membership (str): - Required. The name of the fleet membership - resource to import. - platform_version (str): - Required. The platform version for the cluster (e.g. - ``1.19.0-gke.1000``). - - You can list all supported versions on a given Google Cloud - region by calling - [GetAttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedServerConfig]. - distribution (str): - Required. The Kubernetes distribution of the underlying - attached cluster. - - Supported values: ["eks", "aks", "generic"]. - proxy_config (google.cloud.gke_multicloud_v1.types.AttachedProxyConfig): - Optional. Proxy configuration for outbound - HTTP(S) traffic. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - fleet_membership: str = proto.Field( - proto.STRING, - number=3, - ) - platform_version: str = proto.Field( - proto.STRING, - number=4, - ) - distribution: str = proto.Field( - proto.STRING, - number=5, - ) - proxy_config: attached_resources.AttachedProxyConfig = proto.Field( - proto.MESSAGE, - number=6, - message=attached_resources.AttachedProxyConfig, - ) - - -class UpdateAttachedClusterRequest(proto.Message): - r"""Request message for ``AttachedClusters.UpdateAttachedCluster`` - method. - - Attributes: - attached_cluster (google.cloud.gke_multicloud_v1.types.AttachedCluster): - Required. The - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource to update. - validate_only (bool): - If set, only validate the request, but do not - actually update the cluster. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask of fields to update. At least one path must - be supplied in this field. The elements of the repeated - paths field can only include these fields from - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]: - - - ``annotations``. - - ``authorization.admin_groups``. - - ``authorization.admin_users``. - - ``binary_authorization.evaluation_mode``. - - ``description``. - - ``logging_config.component_config.enable_components``. - - ``monitoring_config.managed_prometheus_config.enabled``. - - ``platform_version``. - - ``proxy_config.kubernetes_secret.name``. - - ``proxy_config.kubernetes_secret.namespace``. - - ``security_posture_config.vulnerability_mode`` - - ``monitoring_config.cloud_monitoring_config.enabled`` - """ - - attached_cluster: attached_resources.AttachedCluster = proto.Field( - proto.MESSAGE, - number=1, - message=attached_resources.AttachedCluster, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class GetAttachedClusterRequest(proto.Message): - r"""Request message for ``AttachedClusters.GetAttachedCluster`` method. - - Attributes: - name (str): - Required. The name of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource to describe. - - ``AttachedCluster`` names are formatted as - ``projects//locations//attachedClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListAttachedClustersRequest(proto.Message): - r"""Request message for ``AttachedClusters.ListAttachedClusters`` - method. - - Attributes: - parent (str): - Required. The parent location which owns this collection of - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - page_size (int): - The maximum number of items to return. - - If not specified, a default value of 50 will be used by the - service. Regardless of the pageSize value, the response can - include a partial list and a caller should only rely on - response's - [nextPageToken][google.cloud.gkemulticloud.v1.ListAttachedClustersResponse.next_page_token] - to determine if there are more instances left to be queried. - page_token (str): - The ``nextPageToken`` value returned from a previous - [attachedClusters.list][google.cloud.gkemulticloud.v1.AttachedClusters.ListAttachedClusters] - request, if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAttachedClustersResponse(proto.Message): - r"""Response message for ``AttachedClusters.ListAttachedClusters`` - method. - - Attributes: - attached_clusters (MutableSequence[google.cloud.gke_multicloud_v1.types.AttachedCluster]): - A list of - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resources in the specified Google Cloud Platform project and - region region. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - attached_clusters: MutableSequence[attached_resources.AttachedCluster] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=attached_resources.AttachedCluster, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteAttachedClusterRequest(proto.Message): - r"""Request message for ``AttachedClusters.DeleteAttachedCluster`` - method. - - Attributes: - name (str): - Required. The resource name the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - to delete. - - ``AttachedCluster`` names are formatted as - ``projects//locations//attachedClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - validate_only (bool): - If set, only validate the request, but do not - actually delete the resource. - allow_missing (bool): - If set to true, and the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource is not found, the request will succeed but no - action will be taken on the server and a completed - [Operation][google.longrunning.Operation] will be returned. - - Useful for idempotent deletion. - ignore_errors (bool): - If set to true, the deletion of - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] - resource will succeed even if errors occur during deleting - in cluster resources. Using this parameter may result in - orphaned resources in the cluster. - etag (str): - The current etag of the - [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. - - Allows clients to perform deletions through optimistic - concurrency control. - - If the provided etag does not match the current etag of the - cluster, the request will fail and an ABORTED error will be - returned. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - ignore_errors: bool = proto.Field( - proto.BOOL, - number=5, - ) - etag: str = proto.Field( - proto.STRING, - number=4, - ) - - -class GetAttachedServerConfigRequest(proto.Message): - r"""GetAttachedServerConfigRequest gets the server config for - attached clusters. - - Attributes: - name (str): - Required. The name of the - [AttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedServerConfig] - resource to describe. - - ``AttachedServerConfig`` names are formatted as - ``projects//locations//attachedServerConfig``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateAttachedClusterAgentTokenRequest(proto.Message): - r""" - - Attributes: - attached_cluster (str): - Required. - subject_token (str): - Required. - subject_token_type (str): - Required. - version (str): - Required. - grant_type (str): - Optional. - audience (str): - Optional. - scope (str): - Optional. - requested_token_type (str): - Optional. - options (str): - Optional. - """ - - attached_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - subject_token: str = proto.Field( - proto.STRING, - number=2, - ) - subject_token_type: str = proto.Field( - proto.STRING, - number=3, - ) - version: str = proto.Field( - proto.STRING, - number=4, - ) - grant_type: str = proto.Field( - proto.STRING, - number=6, - ) - audience: str = proto.Field( - proto.STRING, - number=7, - ) - scope: str = proto.Field( - proto.STRING, - number=8, - ) - requested_token_type: str = proto.Field( - proto.STRING, - number=9, - ) - options: str = proto.Field( - proto.STRING, - number=10, - ) - - -class GenerateAttachedClusterAgentTokenResponse(proto.Message): - r""" - - Attributes: - access_token (str): - - expires_in (int): - - token_type (str): - - """ - - access_token: str = proto.Field( - proto.STRING, - number=1, - ) - expires_in: int = proto.Field( - proto.INT32, - number=2, - ) - token_type: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_resources.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_resources.py deleted file mode 100644 index 16a3cf1e51b0..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_resources.py +++ /dev/null @@ -1,1424 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.gke_multicloud_v1.types import common_resources -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.gkemulticloud.v1', - manifest={ - 'AwsCluster', - 'AwsControlPlane', - 'AwsServicesAuthentication', - 'AwsAuthorization', - 'AwsClusterUser', - 'AwsClusterGroup', - 'AwsDatabaseEncryption', - 'AwsVolumeTemplate', - 'AwsClusterNetworking', - 'AwsNodePool', - 'UpdateSettings', - 'SurgeSettings', - 'AwsNodeManagement', - 'AwsNodeConfig', - 'AwsNodePoolAutoscaling', - 'AwsOpenIdConfig', - 'AwsJsonWebKeys', - 'AwsServerConfig', - 'AwsK8sVersionInfo', - 'AwsSshConfig', - 'AwsProxyConfig', - 'AwsConfigEncryption', - 'AwsInstancePlacement', - 'AwsAutoscalingGroupMetricsCollection', - 'SpotConfig', - 'AwsClusterError', - 'AwsNodePoolError', - }, -) - - -class AwsCluster(proto.Message): - r"""An Anthos cluster running on AWS. - - Attributes: - name (str): - The name of this resource. - - Cluster names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - description (str): - Optional. A human readable description of - this cluster. Cannot be longer than 255 UTF-8 - encoded bytes. - networking (google.cloud.gke_multicloud_v1.types.AwsClusterNetworking): - Required. Cluster-wide networking - configuration. - aws_region (str): - Required. The AWS region where the cluster runs. - - Each Google Cloud region supports a subset of nearby AWS - regions. You can call - [GetAwsServerConfig][google.cloud.gkemulticloud.v1.AwsClusters.GetAwsServerConfig] - to list all supported AWS regions within a given Google - Cloud region. - control_plane (google.cloud.gke_multicloud_v1.types.AwsControlPlane): - Required. Configuration related to the - cluster control plane. - authorization (google.cloud.gke_multicloud_v1.types.AwsAuthorization): - Required. Configuration related to the - cluster RBAC settings. - state (google.cloud.gke_multicloud_v1.types.AwsCluster.State): - Output only. The current state of the - cluster. - endpoint (str): - Output only. The endpoint of the cluster's - API server. - uid (str): - Output only. A globally unique identifier for - the cluster. - reconciling (bool): - Output only. If set, there are currently - changes in flight to the cluster. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this cluster - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this cluster - was last updated. - etag (str): - Allows clients to perform consistent - read-modify-writes through optimistic - concurrency control. - - Can be sent on update and delete requests to - ensure the client has an up-to-date value before - proceeding. - annotations (MutableMapping[str, str]): - Optional. Annotations on the cluster. - - This field has the same restrictions as Kubernetes - annotations. The total size of all keys and values combined - is limited to 256k. Key can have 2 segments: prefix - (optional) and name (required), separated by a slash (/). - Prefix must be a DNS subdomain. Name must be 63 characters - or less, begin and end with alphanumerics, with dashes (-), - underscores (_), dots (.), and alphanumerics between. - workload_identity_config (google.cloud.gke_multicloud_v1.types.WorkloadIdentityConfig): - Output only. Workload Identity settings. - cluster_ca_certificate (str): - Output only. PEM encoded x509 certificate of - the cluster root of trust. - fleet (google.cloud.gke_multicloud_v1.types.Fleet): - Required. Fleet configuration. - logging_config (google.cloud.gke_multicloud_v1.types.LoggingConfig): - Optional. Logging configuration for this - cluster. - errors (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsClusterError]): - Output only. A set of errors found in the - cluster. - monitoring_config (google.cloud.gke_multicloud_v1.types.MonitoringConfig): - Optional. Monitoring configuration for this - cluster. - binary_authorization (google.cloud.gke_multicloud_v1.types.BinaryAuthorization): - Optional. Binary Authorization configuration - for this cluster. - """ - class State(proto.Enum): - r"""The lifecycle state of the cluster. - - Values: - STATE_UNSPECIFIED (0): - Not set. - PROVISIONING (1): - The PROVISIONING state indicates the cluster - is being created. - RUNNING (2): - The RUNNING state indicates the cluster has - been created and is fully usable. - RECONCILING (3): - The RECONCILING state indicates that some - work is actively being done on the cluster, such - as upgrading the control plane replicas. - STOPPING (4): - The STOPPING state indicates the cluster is - being deleted. - ERROR (5): - The ERROR state indicates the cluster is in a - broken unrecoverable state. - DEGRADED (6): - The DEGRADED state indicates the cluster - requires user action to restore full - functionality. - """ - STATE_UNSPECIFIED = 0 - PROVISIONING = 1 - RUNNING = 2 - RECONCILING = 3 - STOPPING = 4 - ERROR = 5 - DEGRADED = 6 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - networking: 'AwsClusterNetworking' = proto.Field( - proto.MESSAGE, - number=3, - message='AwsClusterNetworking', - ) - aws_region: str = proto.Field( - proto.STRING, - number=4, - ) - control_plane: 'AwsControlPlane' = proto.Field( - proto.MESSAGE, - number=5, - message='AwsControlPlane', - ) - authorization: 'AwsAuthorization' = proto.Field( - proto.MESSAGE, - number=15, - message='AwsAuthorization', - ) - state: State = proto.Field( - proto.ENUM, - number=7, - enum=State, - ) - endpoint: str = proto.Field( - proto.STRING, - number=8, - ) - uid: str = proto.Field( - proto.STRING, - number=9, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=10, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=13, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=14, - ) - workload_identity_config: common_resources.WorkloadIdentityConfig = proto.Field( - proto.MESSAGE, - number=16, - message=common_resources.WorkloadIdentityConfig, - ) - cluster_ca_certificate: str = proto.Field( - proto.STRING, - number=17, - ) - fleet: common_resources.Fleet = proto.Field( - proto.MESSAGE, - number=18, - message=common_resources.Fleet, - ) - logging_config: common_resources.LoggingConfig = proto.Field( - proto.MESSAGE, - number=19, - message=common_resources.LoggingConfig, - ) - errors: MutableSequence['AwsClusterError'] = proto.RepeatedField( - proto.MESSAGE, - number=20, - message='AwsClusterError', - ) - monitoring_config: common_resources.MonitoringConfig = proto.Field( - proto.MESSAGE, - number=21, - message=common_resources.MonitoringConfig, - ) - binary_authorization: common_resources.BinaryAuthorization = proto.Field( - proto.MESSAGE, - number=22, - message=common_resources.BinaryAuthorization, - ) - - -class AwsControlPlane(proto.Message): - r"""ControlPlane defines common parameters between control plane - nodes. - - Attributes: - version (str): - Required. The Kubernetes version to run on control plane - replicas (e.g. ``1.19.10-gke.1000``). - - You can list all supported versions on a given Google Cloud - region by calling - [GetAwsServerConfig][google.cloud.gkemulticloud.v1.AwsClusters.GetAwsServerConfig]. - instance_type (str): - Optional. The AWS instance type. - - When unspecified, it uses a default based on the - cluster's version. - ssh_config (google.cloud.gke_multicloud_v1.types.AwsSshConfig): - Optional. SSH configuration for how to access - the underlying control plane machines. - subnet_ids (MutableSequence[str]): - Required. The list of subnets where control - plane replicas will run. A replica will be - provisioned on each subnet and up to three - values can be provided. - Each subnet must be in a different AWS - Availability Zone (AZ). - security_group_ids (MutableSequence[str]): - Optional. The IDs of additional security - groups to add to control plane replicas. The - Anthos Multi-Cloud API will automatically create - and manage security groups with the minimum - rules needed for a functioning cluster. - iam_instance_profile (str): - Required. The name or ARN of the AWS IAM - instance profile to assign to each control plane - replica. - root_volume (google.cloud.gke_multicloud_v1.types.AwsVolumeTemplate): - Optional. Configuration related to the root - volume provisioned for each control plane - replica. - - Volumes will be provisioned in the availability - zone associated with the corresponding subnet. - - When unspecified, it defaults to 32 GiB with the - GP2 volume type. - main_volume (google.cloud.gke_multicloud_v1.types.AwsVolumeTemplate): - Optional. Configuration related to the main - volume provisioned for each control plane - replica. The main volume is in charge of storing - all of the cluster's etcd state. - - Volumes will be provisioned in the availability - zone associated with the corresponding subnet. - - When unspecified, it defaults to 8 GiB with the - GP2 volume type. - database_encryption (google.cloud.gke_multicloud_v1.types.AwsDatabaseEncryption): - Required. The ARN of the AWS KMS key used to - encrypt cluster secrets. - tags (MutableMapping[str, str]): - Optional. A set of AWS resource tags to propagate to all - underlying managed AWS resources. - - Specify at most 50 pairs containing alphanumerics, spaces, - and symbols (.+-=_:@/). Keys can be up to 127 Unicode - characters. Values can be up to 255 Unicode characters. - aws_services_authentication (google.cloud.gke_multicloud_v1.types.AwsServicesAuthentication): - Required. Authentication configuration for - management of AWS resources. - proxy_config (google.cloud.gke_multicloud_v1.types.AwsProxyConfig): - Optional. Proxy configuration for outbound - HTTP(S) traffic. - config_encryption (google.cloud.gke_multicloud_v1.types.AwsConfigEncryption): - Required. Config encryption for user data. - instance_placement (google.cloud.gke_multicloud_v1.types.AwsInstancePlacement): - Optional. The placement to use on control - plane instances. When unspecified, the VPC's - default tenancy will be used. - """ - - version: str = proto.Field( - proto.STRING, - number=1, - ) - instance_type: str = proto.Field( - proto.STRING, - number=2, - ) - ssh_config: 'AwsSshConfig' = proto.Field( - proto.MESSAGE, - number=14, - message='AwsSshConfig', - ) - subnet_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - security_group_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - iam_instance_profile: str = proto.Field( - proto.STRING, - number=7, - ) - root_volume: 'AwsVolumeTemplate' = proto.Field( - proto.MESSAGE, - number=8, - message='AwsVolumeTemplate', - ) - main_volume: 'AwsVolumeTemplate' = proto.Field( - proto.MESSAGE, - number=9, - message='AwsVolumeTemplate', - ) - database_encryption: 'AwsDatabaseEncryption' = proto.Field( - proto.MESSAGE, - number=10, - message='AwsDatabaseEncryption', - ) - tags: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=11, - ) - aws_services_authentication: 'AwsServicesAuthentication' = proto.Field( - proto.MESSAGE, - number=12, - message='AwsServicesAuthentication', - ) - proxy_config: 'AwsProxyConfig' = proto.Field( - proto.MESSAGE, - number=16, - message='AwsProxyConfig', - ) - config_encryption: 'AwsConfigEncryption' = proto.Field( - proto.MESSAGE, - number=17, - message='AwsConfigEncryption', - ) - instance_placement: 'AwsInstancePlacement' = proto.Field( - proto.MESSAGE, - number=18, - message='AwsInstancePlacement', - ) - - -class AwsServicesAuthentication(proto.Message): - r"""Authentication configuration for the management of AWS - resources. - - Attributes: - role_arn (str): - Required. The Amazon Resource Name (ARN) of - the role that the Anthos Multi-Cloud API will - assume when managing AWS resources on your - account. - role_session_name (str): - Optional. An identifier for the assumed role session. - - When unspecified, it defaults to - ``multicloud-service-agent``. - """ - - role_arn: str = proto.Field( - proto.STRING, - number=1, - ) - role_session_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AwsAuthorization(proto.Message): - r"""Configuration related to the cluster RBAC settings. - - Attributes: - admin_users (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsClusterUser]): - Optional. Users that can perform operations as a cluster - admin. A managed ClusterRoleBinding will be created to grant - the ``cluster-admin`` ClusterRole to the users. Up to ten - admin users can be provided. - - For more info on RBAC, see - https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles - admin_groups (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsClusterGroup]): - Optional. Groups of users that can perform operations as a - cluster admin. A managed ClusterRoleBinding will be created - to grant the ``cluster-admin`` ClusterRole to the groups. Up - to ten admin groups can be provided. - - For more info on RBAC, see - https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles - """ - - admin_users: MutableSequence['AwsClusterUser'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AwsClusterUser', - ) - admin_groups: MutableSequence['AwsClusterGroup'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AwsClusterGroup', - ) - - -class AwsClusterUser(proto.Message): - r"""Identities of a user-type subject for AWS clusters. - - Attributes: - username (str): - Required. The name of the user, e.g. - ``my-gcp-id@gmail.com``. - """ - - username: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AwsClusterGroup(proto.Message): - r"""Identities of a group-type subject for AWS clusters. - - Attributes: - group (str): - Required. The name of the group, e.g. - ``my-group@domain.com``. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AwsDatabaseEncryption(proto.Message): - r"""Configuration related to application-layer secrets - encryption. - - Attributes: - kms_key_arn (str): - Required. The ARN of the AWS KMS key used to - encrypt cluster secrets. - """ - - kms_key_arn: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AwsVolumeTemplate(proto.Message): - r"""Configuration template for AWS EBS volumes. - - Attributes: - size_gib (int): - Optional. The size of the volume, in GiBs. - - When unspecified, a default value is provided. - See the specific reference in the parent - resource. - volume_type (google.cloud.gke_multicloud_v1.types.AwsVolumeTemplate.VolumeType): - Optional. Type of the EBS volume. - - When unspecified, it defaults to GP2 volume. - iops (int): - Optional. The number of I/O operations per - second (IOPS) to provision for GP3 volume. - throughput (int): - Optional. The throughput that the volume supports, in MiB/s. - Only valid if volume_type is GP3. - - If the volume_type is GP3 and this is not speficied, it - defaults to 125. - kms_key_arn (str): - Optional. The Amazon Resource Name (ARN) of - the Customer Managed Key (CMK) used to encrypt - AWS EBS volumes. - - If not specified, the default Amazon managed key - associated to the AWS region where this cluster - runs will be used. - """ - class VolumeType(proto.Enum): - r"""Types of supported EBS volumes. We currently only support GP2 - or GP3 volumes. - See - https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html - for more information. - - Values: - VOLUME_TYPE_UNSPECIFIED (0): - Not set. - GP2 (1): - GP2 (General Purpose SSD volume type). - GP3 (2): - GP3 (General Purpose SSD volume type). - """ - VOLUME_TYPE_UNSPECIFIED = 0 - GP2 = 1 - GP3 = 2 - - size_gib: int = proto.Field( - proto.INT32, - number=1, - ) - volume_type: VolumeType = proto.Field( - proto.ENUM, - number=2, - enum=VolumeType, - ) - iops: int = proto.Field( - proto.INT32, - number=3, - ) - throughput: int = proto.Field( - proto.INT32, - number=5, - ) - kms_key_arn: str = proto.Field( - proto.STRING, - number=4, - ) - - -class AwsClusterNetworking(proto.Message): - r"""ClusterNetworking defines cluster-wide networking - configuration. - Anthos clusters on AWS run on a single VPC. This includes - control plane replicas and node pool nodes. - - Attributes: - vpc_id (str): - Required. The VPC associated with the - cluster. All component clusters (i.e. control - plane and node pools) run on a single VPC. - - This field cannot be changed after creation. - pod_address_cidr_blocks (MutableSequence[str]): - Required. All pods in the cluster are - assigned an IPv4 address from these ranges. Only - a single range is supported. This field cannot - be changed after creation. - service_address_cidr_blocks (MutableSequence[str]): - Required. All services in the cluster are - assigned an IPv4 address from these ranges. Only - a single range is supported. This field cannot - be changed after creation. - per_node_pool_sg_rules_disabled (bool): - Optional. Disable the per node pool subnet - security group rules on the control plane - security group. When set to true, you must also - provide one or more security groups that ensure - node pools are able to send requests to the - control plane on TCP/443 and TCP/8132. Failure - to do so may result in unavailable node pools. - """ - - vpc_id: str = proto.Field( - proto.STRING, - number=1, - ) - pod_address_cidr_blocks: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - service_address_cidr_blocks: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - per_node_pool_sg_rules_disabled: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class AwsNodePool(proto.Message): - r"""An Anthos node pool running on AWS. - - Attributes: - name (str): - The name of this resource. - - Node pool names are formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - For more details on Google Cloud resource names, see - `Resource - Names `__ - version (str): - Required. The Kubernetes version to run on this node pool - (e.g. ``1.19.10-gke.1000``). - - You can list all supported versions on a given Google Cloud - region by calling - [GetAwsServerConfig][google.cloud.gkemulticloud.v1.AwsClusters.GetAwsServerConfig]. - config (google.cloud.gke_multicloud_v1.types.AwsNodeConfig): - Required. The configuration of the node pool. - autoscaling (google.cloud.gke_multicloud_v1.types.AwsNodePoolAutoscaling): - Required. Autoscaler configuration for this - node pool. - subnet_id (str): - Required. The subnet where the node pool node - run. - state (google.cloud.gke_multicloud_v1.types.AwsNodePool.State): - Output only. The lifecycle state of the node - pool. - uid (str): - Output only. A globally unique identifier for - the node pool. - reconciling (bool): - Output only. If set, there are currently - changes in flight to the node pool. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this node pool - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this node pool - was last updated. - etag (str): - Allows clients to perform consistent - read-modify-writes through optimistic - concurrency control. - - Can be sent on update and delete requests to - ensure the client has an up-to-date value before - proceeding. - annotations (MutableMapping[str, str]): - Optional. Annotations on the node pool. - - This field has the same restrictions as Kubernetes - annotations. The total size of all keys and values combined - is limited to 256k. Key can have 2 segments: prefix - (optional) and name (required), separated by a slash (/). - Prefix must be a DNS subdomain. Name must be 63 characters - or less, begin and end with alphanumerics, with dashes (-), - underscores (_), dots (.), and alphanumerics between. - max_pods_constraint (google.cloud.gke_multicloud_v1.types.MaxPodsConstraint): - Required. The constraint on the maximum - number of pods that can be run simultaneously on - a node in the node pool. - errors (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsNodePoolError]): - Output only. A set of errors found in the - node pool. - management (google.cloud.gke_multicloud_v1.types.AwsNodeManagement): - Optional. The Management configuration for - this node pool. - kubelet_config (google.cloud.gke_multicloud_v1.types.NodeKubeletConfig): - Optional. Node kubelet configs. - update_settings (google.cloud.gke_multicloud_v1.types.UpdateSettings): - Optional. Update settings control the speed - and disruption of the update. - """ - class State(proto.Enum): - r"""The lifecycle state of the node pool. - - Values: - STATE_UNSPECIFIED (0): - Not set. - PROVISIONING (1): - The PROVISIONING state indicates the node - pool is being created. - RUNNING (2): - The RUNNING state indicates the node pool has - been created and is fully usable. - RECONCILING (3): - The RECONCILING state indicates that the node - pool is being reconciled. - STOPPING (4): - The STOPPING state indicates the node pool is - being deleted. - ERROR (5): - The ERROR state indicates the node pool is in - a broken unrecoverable state. - DEGRADED (6): - The DEGRADED state indicates the node pool - requires user action to restore full - functionality. - """ - STATE_UNSPECIFIED = 0 - PROVISIONING = 1 - RUNNING = 2 - RECONCILING = 3 - STOPPING = 4 - ERROR = 5 - DEGRADED = 6 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=3, - ) - config: 'AwsNodeConfig' = proto.Field( - proto.MESSAGE, - number=28, - message='AwsNodeConfig', - ) - autoscaling: 'AwsNodePoolAutoscaling' = proto.Field( - proto.MESSAGE, - number=25, - message='AwsNodePoolAutoscaling', - ) - subnet_id: str = proto.Field( - proto.STRING, - number=6, - ) - state: State = proto.Field( - proto.ENUM, - number=16, - enum=State, - ) - uid: str = proto.Field( - proto.STRING, - number=17, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=18, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=20, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=21, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=22, - ) - max_pods_constraint: common_resources.MaxPodsConstraint = proto.Field( - proto.MESSAGE, - number=27, - message=common_resources.MaxPodsConstraint, - ) - errors: MutableSequence['AwsNodePoolError'] = proto.RepeatedField( - proto.MESSAGE, - number=29, - message='AwsNodePoolError', - ) - management: 'AwsNodeManagement' = proto.Field( - proto.MESSAGE, - number=30, - message='AwsNodeManagement', - ) - kubelet_config: common_resources.NodeKubeletConfig = proto.Field( - proto.MESSAGE, - number=31, - message=common_resources.NodeKubeletConfig, - ) - update_settings: 'UpdateSettings' = proto.Field( - proto.MESSAGE, - number=32, - message='UpdateSettings', - ) - - -class UpdateSettings(proto.Message): - r"""UpdateSettings control the level of parallelism and the level of - disruption caused during the update of a node pool. - - These settings are applicable when the node pool update requires - replacing the existing node pool nodes with the updated ones. - - UpdateSettings are optional. When UpdateSettings are not specified - during the node pool creation, a default is chosen based on the - parent cluster's version. For clusters with minor version 1.27 and - later, a default surge_settings configuration with max_surge = 1 and - max_unavailable = 0 is used. For clusters with older versions, node - pool updates use the traditional rolling update mechanism of - updating one node at a time in a "terminate before create" fashion - and update_settings is not applicable. - - Set the surge_settings parameter to use the Surge Update mechanism - for the rolling update of node pool nodes. - - 1. max_surge controls the number of additional nodes that can be - created beyond the current size of the node pool temporarily for - the time of the update to increase the number of available nodes. - 2. max_unavailable controls the number of nodes that can be - simultaneously unavailable during the update. - 3. (max_surge + max_unavailable) determines the level of parallelism - (i.e., the number of nodes being updated at the same time). - - Attributes: - surge_settings (google.cloud.gke_multicloud_v1.types.SurgeSettings): - Optional. Settings for surge update. - """ - - surge_settings: 'SurgeSettings' = proto.Field( - proto.MESSAGE, - number=1, - message='SurgeSettings', - ) - - -class SurgeSettings(proto.Message): - r"""SurgeSettings contains the parameters for Surge update. - - Attributes: - max_surge (int): - Optional. The maximum number of nodes that - can be created beyond the current size of the - node pool during the update process. - max_unavailable (int): - Optional. The maximum number of nodes that - can be simultaneously unavailable during the - update process. A node is considered unavailable - if its status is not Ready. - """ - - max_surge: int = proto.Field( - proto.INT32, - number=1, - ) - max_unavailable: int = proto.Field( - proto.INT32, - number=2, - ) - - -class AwsNodeManagement(proto.Message): - r"""AwsNodeManagement defines the set of node management features - turned on for an AWS node pool. - - Attributes: - auto_repair (bool): - Optional. Whether or not the nodes will be - automatically repaired. When set to true, the - nodes in this node pool will be monitored and if - they fail health checks consistently over a - period of time, an automatic repair action will - be triggered to replace them with new nodes. - """ - - auto_repair: bool = proto.Field( - proto.BOOL, - number=1, - ) - - -class AwsNodeConfig(proto.Message): - r"""Parameters that describe the nodes in a cluster. - - Attributes: - instance_type (str): - Optional. The EC2 instance type when creating - on-Demand instances. - If unspecified during node pool creation, a - default will be chosen based on the node pool - version, and assigned to this field. - root_volume (google.cloud.gke_multicloud_v1.types.AwsVolumeTemplate): - Optional. Template for the root volume - provisioned for node pool nodes. Volumes will be - provisioned in the availability zone assigned to - the node pool subnet. - - When unspecified, it defaults to 32 GiB with the - GP2 volume type. - taints (MutableSequence[google.cloud.gke_multicloud_v1.types.NodeTaint]): - Optional. The initial taints assigned to - nodes of this node pool. - labels (MutableMapping[str, str]): - Optional. The initial labels assigned to - nodes of this node pool. An object containing a - list of "key": value pairs. Example: { "name": - "wrench", "mass": "1.3kg", "count": "3" }. - tags (MutableMapping[str, str]): - Optional. Key/value metadata to assign to each underlying - AWS resource. Specify at most 50 pairs containing - alphanumerics, spaces, and symbols (.+-=_:@/). Keys can be - up to 127 Unicode characters. Values can be up to 255 - Unicode characters. - iam_instance_profile (str): - Required. The name or ARN of the AWS IAM - instance profile to assign to nodes in the pool. - image_type (str): - Optional. The OS image type to use on node pool instances. - Can be unspecified, or have a value of ``ubuntu``. - - When unspecified, it defaults to ``ubuntu``. - ssh_config (google.cloud.gke_multicloud_v1.types.AwsSshConfig): - Optional. The SSH configuration. - security_group_ids (MutableSequence[str]): - Optional. The IDs of additional security - groups to add to nodes in this pool. The manager - will automatically create security groups with - minimum rules needed for a functioning cluster. - proxy_config (google.cloud.gke_multicloud_v1.types.AwsProxyConfig): - Optional. Proxy configuration for outbound - HTTP(S) traffic. - config_encryption (google.cloud.gke_multicloud_v1.types.AwsConfigEncryption): - Required. Config encryption for user data. - instance_placement (google.cloud.gke_multicloud_v1.types.AwsInstancePlacement): - Optional. Placement related info for this - node. When unspecified, the VPC's default - tenancy will be used. - autoscaling_metrics_collection (google.cloud.gke_multicloud_v1.types.AwsAutoscalingGroupMetricsCollection): - Optional. Configuration related to CloudWatch - metrics collection on the Auto Scaling group of - the node pool. - - When unspecified, metrics collection is - disabled. - spot_config (google.cloud.gke_multicloud_v1.types.SpotConfig): - Optional. Configuration for provisioning EC2 Spot instances - - When specified, the node pool will provision Spot instances - from the set of spot_config.instance_types. This field is - mutually exclusive with ``instance_type``. - """ - - instance_type: str = proto.Field( - proto.STRING, - number=1, - ) - root_volume: 'AwsVolumeTemplate' = proto.Field( - proto.MESSAGE, - number=2, - message='AwsVolumeTemplate', - ) - taints: MutableSequence[common_resources.NodeTaint] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=common_resources.NodeTaint, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - tags: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - iam_instance_profile: str = proto.Field( - proto.STRING, - number=6, - ) - image_type: str = proto.Field( - proto.STRING, - number=11, - ) - ssh_config: 'AwsSshConfig' = proto.Field( - proto.MESSAGE, - number=9, - message='AwsSshConfig', - ) - security_group_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - proxy_config: 'AwsProxyConfig' = proto.Field( - proto.MESSAGE, - number=12, - message='AwsProxyConfig', - ) - config_encryption: 'AwsConfigEncryption' = proto.Field( - proto.MESSAGE, - number=13, - message='AwsConfigEncryption', - ) - instance_placement: 'AwsInstancePlacement' = proto.Field( - proto.MESSAGE, - number=14, - message='AwsInstancePlacement', - ) - autoscaling_metrics_collection: 'AwsAutoscalingGroupMetricsCollection' = proto.Field( - proto.MESSAGE, - number=15, - message='AwsAutoscalingGroupMetricsCollection', - ) - spot_config: 'SpotConfig' = proto.Field( - proto.MESSAGE, - number=16, - message='SpotConfig', - ) - - -class AwsNodePoolAutoscaling(proto.Message): - r"""AwsNodePoolAutoscaling contains information required by - cluster autoscaler to adjust the size of the node pool to the - current cluster usage. - - Attributes: - min_node_count (int): - Required. Minimum number of nodes in the node pool. Must be - greater than or equal to 1 and less than or equal to - max_node_count. - max_node_count (int): - Required. Maximum number of nodes in the node pool. Must be - greater than or equal to min_node_count and less than or - equal to 50. - """ - - min_node_count: int = proto.Field( - proto.INT32, - number=1, - ) - max_node_count: int = proto.Field( - proto.INT32, - number=2, - ) - - -class AwsOpenIdConfig(proto.Message): - r"""AwsOpenIdConfig is an OIDC discovery document for the - cluster. See the OpenID Connect Discovery 1.0 specification for - details. - - Attributes: - issuer (str): - OIDC Issuer. - jwks_uri (str): - JSON Web Key uri. - response_types_supported (MutableSequence[str]): - Supported response types. - subject_types_supported (MutableSequence[str]): - Supported subject types. - id_token_signing_alg_values_supported (MutableSequence[str]): - supported ID Token signing Algorithms. - claims_supported (MutableSequence[str]): - Supported claims. - grant_types (MutableSequence[str]): - Supported grant types. - """ - - issuer: str = proto.Field( - proto.STRING, - number=1, - ) - jwks_uri: str = proto.Field( - proto.STRING, - number=2, - ) - response_types_supported: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - subject_types_supported: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - id_token_signing_alg_values_supported: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - claims_supported: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - grant_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - - -class AwsJsonWebKeys(proto.Message): - r"""AwsJsonWebKeys is a valid JSON Web Key Set as specififed in - RFC 7517. - - Attributes: - keys (MutableSequence[google.cloud.gke_multicloud_v1.types.Jwk]): - The public component of the keys used by the - cluster to sign token requests. - """ - - keys: MutableSequence[common_resources.Jwk] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=common_resources.Jwk, - ) - - -class AwsServerConfig(proto.Message): - r"""AwsServerConfig is the configuration of GKE cluster on AWS. - - Attributes: - name (str): - The resource name of the config. - valid_versions (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsK8sVersionInfo]): - List of all released Kubernetes versions, including ones - which are end of life and can no longer be used. Filter by - the ``enabled`` property to limit to currently available - versions. Valid versions supported for both create and - update operations - supported_aws_regions (MutableSequence[str]): - The list of supported AWS regions. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - valid_versions: MutableSequence['AwsK8sVersionInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AwsK8sVersionInfo', - ) - supported_aws_regions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class AwsK8sVersionInfo(proto.Message): - r"""Kubernetes version information of GKE cluster on AWS. - - Attributes: - version (str): - Kubernetes version name. - enabled (bool): - Optional. True if the version is available - for cluster creation. If a version is enabled - for creation, it can be used to create new - clusters. Otherwise, cluster creation will fail. - However, cluster upgrade operations may succeed, - even if the version is not enabled. - end_of_life (bool): - Optional. True if this cluster version - belongs to a minor version that has reached its - end of life and is no longer in scope to receive - security and bug fixes. - end_of_life_date (google.type.date_pb2.Date): - Optional. The estimated date (in Pacific Time) when this - cluster version will reach its end of life. Or if this - version is no longer supported (the ``end_of_life`` field is - true), this is the actual date (in Pacific time) when the - version reached its end of life. - release_date (google.type.date_pb2.Date): - Optional. The date (in Pacific Time) when the - cluster version was released. - """ - - version: str = proto.Field( - proto.STRING, - number=1, - ) - enabled: bool = proto.Field( - proto.BOOL, - number=3, - ) - end_of_life: bool = proto.Field( - proto.BOOL, - number=4, - ) - end_of_life_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=5, - message=date_pb2.Date, - ) - release_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=6, - message=date_pb2.Date, - ) - - -class AwsSshConfig(proto.Message): - r"""SSH configuration for AWS resources. - - Attributes: - ec2_key_pair (str): - Required. The name of the EC2 key pair used - to login into cluster machines. - """ - - ec2_key_pair: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AwsProxyConfig(proto.Message): - r"""Details of a proxy config stored in AWS Secret Manager. - - Attributes: - secret_arn (str): - The ARN of the AWS Secret Manager secret that contains the - HTTP(S) proxy configuration. - - The secret must be a JSON encoded proxy configuration as - described in - https://cloud.google.com/kubernetes-engine/multi-cloud/docs/aws/how-to/use-a-proxy#create_a_proxy_configuration_file - secret_version (str): - The version string of the AWS Secret Manager - secret that contains the HTTP(S) proxy - configuration. - """ - - secret_arn: str = proto.Field( - proto.STRING, - number=1, - ) - secret_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AwsConfigEncryption(proto.Message): - r"""Config encryption for user data. - - Attributes: - kms_key_arn (str): - Required. The ARN of the AWS KMS key used to - encrypt user data. - """ - - kms_key_arn: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AwsInstancePlacement(proto.Message): - r"""Details of placement information for an instance. Limitations for - using the ``host`` tenancy: - - - T3 instances that use the unlimited CPU credit option don't - support host tenancy. - - Attributes: - tenancy (google.cloud.gke_multicloud_v1.types.AwsInstancePlacement.Tenancy): - Required. The tenancy for instance. - """ - class Tenancy(proto.Enum): - r"""Tenancy defines how EC2 instances are distributed across - physical hardware. - - Values: - TENANCY_UNSPECIFIED (0): - Not set. - DEFAULT (1): - Use default VPC tenancy. - DEDICATED (2): - Run a dedicated instance. - HOST (3): - Launch this instance to a dedicated host. - """ - TENANCY_UNSPECIFIED = 0 - DEFAULT = 1 - DEDICATED = 2 - HOST = 3 - - tenancy: Tenancy = proto.Field( - proto.ENUM, - number=1, - enum=Tenancy, - ) - - -class AwsAutoscalingGroupMetricsCollection(proto.Message): - r"""Configuration related to CloudWatch metrics collection in an - AWS Auto Scaling group. - - Attributes: - granularity (str): - Required. The frequency at which EC2 Auto - Scaling sends aggregated data to AWS CloudWatch. - The only valid value is "1Minute". - metrics (MutableSequence[str]): - Optional. The metrics to enable. For a list of valid - metrics, see - https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_EnableMetricsCollection.html. - If you specify Granularity and don't specify any metrics, - all metrics are enabled. - """ - - granularity: str = proto.Field( - proto.STRING, - number=1, - ) - metrics: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class SpotConfig(proto.Message): - r"""SpotConfig has configuration info for Spot node. - - Attributes: - instance_types (MutableSequence[str]): - Required. A list of instance types for - creating spot node pool. - """ - - instance_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class AwsClusterError(proto.Message): - r"""AwsClusterError describes errors found on AWS clusters. - - Attributes: - message (str): - Human-friendly description of the error. - """ - - message: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AwsNodePoolError(proto.Message): - r"""AwsNodePoolError describes errors found on AWS node pools. - - Attributes: - message (str): - Human-friendly description of the error. - """ - - message: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_service.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_service.py deleted file mode 100644 index 61b6badef56f..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/aws_service.py +++ /dev/null @@ -1,850 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.gke_multicloud_v1.types import aws_resources -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.gkemulticloud.v1', - manifest={ - 'CreateAwsClusterRequest', - 'UpdateAwsClusterRequest', - 'GetAwsClusterRequest', - 'ListAwsClustersRequest', - 'ListAwsClustersResponse', - 'DeleteAwsClusterRequest', - 'CreateAwsNodePoolRequest', - 'UpdateAwsNodePoolRequest', - 'RollbackAwsNodePoolUpdateRequest', - 'GetAwsNodePoolRequest', - 'ListAwsNodePoolsRequest', - 'ListAwsNodePoolsResponse', - 'DeleteAwsNodePoolRequest', - 'GetAwsOpenIdConfigRequest', - 'GetAwsJsonWebKeysRequest', - 'GetAwsServerConfigRequest', - 'GenerateAwsAccessTokenRequest', - 'GenerateAwsAccessTokenResponse', - 'GenerateAwsClusterAgentTokenRequest', - 'GenerateAwsClusterAgentTokenResponse', - }, -) - - -class CreateAwsClusterRequest(proto.Message): - r"""Request message for ``AwsClusters.CreateAwsCluster`` method. - - Attributes: - parent (str): - Required. The parent location where this - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - aws_cluster (google.cloud.gke_multicloud_v1.types.AwsCluster): - Required. The specification of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] to - create. - aws_cluster_id (str): - Required. A client provided ID the resource. Must be unique - within the parent resource. - - The provided ID will be part of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource name formatted as - ``projects//locations//awsClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - validate_only (bool): - If set, only validate the request, but do not - actually create the cluster. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - aws_cluster: aws_resources.AwsCluster = proto.Field( - proto.MESSAGE, - number=2, - message=aws_resources.AwsCluster, - ) - aws_cluster_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateAwsClusterRequest(proto.Message): - r"""Request message for ``AwsClusters.UpdateAwsCluster`` method. - - Attributes: - aws_cluster (google.cloud.gke_multicloud_v1.types.AwsCluster): - Required. The - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource to update. - validate_only (bool): - If set, only validate the request, but do not - actually update the cluster. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask of fields to update. At least one path must - be supplied in this field. The elements of the repeated - paths field can only include these fields from - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]: - - - ``description``. - - ``annotations``. - - ``control_plane.version``. - - ``authorization.admin_users``. - - ``authorization.admin_groups``. - - ``binary_authorization.evaluation_mode``. - - ``control_plane.aws_services_authentication.role_arn``. - - ``control_plane.aws_services_authentication.role_session_name``. - - ``control_plane.config_encryption.kms_key_arn``. - - ``control_plane.instance_type``. - - ``control_plane.security_group_ids``. - - ``control_plane.proxy_config``. - - ``control_plane.proxy_config.secret_arn``. - - ``control_plane.proxy_config.secret_version``. - - ``control_plane.root_volume.size_gib``. - - ``control_plane.root_volume.volume_type``. - - ``control_plane.root_volume.iops``. - - ``control_plane.root_volume.throughput``. - - ``control_plane.root_volume.kms_key_arn``. - - ``control_plane.ssh_config``. - - ``control_plane.ssh_config.ec2_key_pair``. - - ``control_plane.instance_placement.tenancy``. - - ``control_plane.iam_instance_profile``. - - ``logging_config.component_config.enable_components``. - - ``control_plane.tags``. - - ``monitoring_config.managed_prometheus_config.enabled``. - - ``networking.per_node_pool_sg_rules_disabled``. - """ - - aws_cluster: aws_resources.AwsCluster = proto.Field( - proto.MESSAGE, - number=1, - message=aws_resources.AwsCluster, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class GetAwsClusterRequest(proto.Message): - r"""Request message for ``AwsClusters.GetAwsCluster`` method. - - Attributes: - name (str): - Required. The name of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource to describe. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListAwsClustersRequest(proto.Message): - r"""Request message for ``AwsClusters.ListAwsClusters`` method. - - Attributes: - parent (str): - Required. The parent location which owns this collection of - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - page_size (int): - The maximum number of items to return. - - If not specified, a default value of 50 will be used by the - service. Regardless of the pageSize value, the response can - include a partial list and a caller should only rely on - response's - [nextPageToken][google.cloud.gkemulticloud.v1.ListAwsClustersResponse.next_page_token] - to determine if there are more instances left to be queried. - page_token (str): - The ``nextPageToken`` value returned from a previous - [awsClusters.list][google.cloud.gkemulticloud.v1.AwsClusters.ListAwsClusters] - request, if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAwsClustersResponse(proto.Message): - r"""Response message for ``AwsClusters.ListAwsClusters`` method. - - Attributes: - aws_clusters (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsCluster]): - A list of - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resources in the specified Google Cloud Platform project and - region region. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - aws_clusters: MutableSequence[aws_resources.AwsCluster] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=aws_resources.AwsCluster, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteAwsClusterRequest(proto.Message): - r"""Request message for ``AwsClusters.DeleteAwsCluster`` method. - - Attributes: - name (str): - Required. The resource name the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] to - delete. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - validate_only (bool): - If set, only validate the request, but do not - actually delete the resource. - allow_missing (bool): - If set to true, and the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource is not found, the request will succeed but no - action will be taken on the server and a completed - [Operation][google.longrunning.Operation] will be returned. - - Useful for idempotent deletion. - ignore_errors (bool): - Optional. If set to true, the deletion of - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource will succeed even if errors occur during deleting - in cluster resources. Using this parameter may result in - orphaned resources in the cluster. - etag (str): - The current etag of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. - - Allows clients to perform deletions through optimistic - concurrency control. - - If the provided etag does not match the current etag of the - cluster, the request will fail and an ABORTED error will be - returned. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - ignore_errors: bool = proto.Field( - proto.BOOL, - number=5, - ) - etag: str = proto.Field( - proto.STRING, - number=4, - ) - - -class CreateAwsNodePoolRequest(proto.Message): - r"""Response message for ``AwsClusters.CreateAwsNodePool`` method. - - Attributes: - parent (str): - Required. The - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource where this node pool will be created. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - aws_node_pool (google.cloud.gke_multicloud_v1.types.AwsNodePool): - Required. The specification of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] to - create. - aws_node_pool_id (str): - Required. A client provided ID the resource. Must be unique - within the parent resource. - - The provided ID will be part of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource name formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - validate_only (bool): - If set, only validate the request, but do not - actually create the node pool. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - aws_node_pool: aws_resources.AwsNodePool = proto.Field( - proto.MESSAGE, - number=2, - message=aws_resources.AwsNodePool, - ) - aws_node_pool_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateAwsNodePoolRequest(proto.Message): - r"""Request message for ``AwsClusters.UpdateAwsNodePool`` method. - - Attributes: - aws_node_pool (google.cloud.gke_multicloud_v1.types.AwsNodePool): - Required. The - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource to update. - validate_only (bool): - If set, only validate the request, but don't - actually update the node pool. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask of fields to update. At least one path must - be supplied in this field. The elements of the repeated - paths field can only include these fields from - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]: - - - ``annotations``. - - ``version``. - - ``autoscaling.min_node_count``. - - ``autoscaling.max_node_count``. - - ``config.config_encryption.kms_key_arn``. - - ``config.security_group_ids``. - - ``config.root_volume.iops``. - - ``config.root_volume.throughput``. - - ``config.root_volume.kms_key_arn``. - - ``config.root_volume.volume_type``. - - ``config.root_volume.size_gib``. - - ``config.proxy_config``. - - ``config.proxy_config.secret_arn``. - - ``config.proxy_config.secret_version``. - - ``config.ssh_config``. - - ``config.ssh_config.ec2_key_pair``. - - ``config.instance_placement.tenancy``. - - ``config.iam_instance_profile``. - - ``config.labels``. - - ``config.tags``. - - ``config.autoscaling_metrics_collection``. - - ``config.autoscaling_metrics_collection.granularity``. - - ``config.autoscaling_metrics_collection.metrics``. - - ``config.instance_type``. - - ``management.auto_repair``. - - ``management``. - - ``update_settings``. - - ``update_settings.surge_settings``. - - ``update_settings.surge_settings.max_surge``. - - ``update_settings.surge_settings.max_unavailable``. - """ - - aws_node_pool: aws_resources.AwsNodePool = proto.Field( - proto.MESSAGE, - number=1, - message=aws_resources.AwsNodePool, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class RollbackAwsNodePoolUpdateRequest(proto.Message): - r"""Request message for ``AwsClusters.RollbackAwsNodePoolUpdate`` - method. - - Attributes: - name (str): - Required. The name of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource to rollback. - - ``AwsNodePool`` names are formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - respect_pdb (bool): - Optional. Option for rollback to ignore the - PodDisruptionBudget when draining the node pool - nodes. Default value is false. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - respect_pdb: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class GetAwsNodePoolRequest(proto.Message): - r"""Request message for ``AwsClusters.GetAwsNodePool`` method. - - Attributes: - name (str): - Required. The name of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource to describe. - - ``AwsNodePool`` names are formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListAwsNodePoolsRequest(proto.Message): - r"""Request message for ``AwsClusters.ListAwsNodePools`` method. - - Attributes: - parent (str): - Required. The parent ``AwsCluster`` which owns this - collection of - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - page_size (int): - The maximum number of items to return. - - If not specified, a default value of 50 will be used by the - service. Regardless of the pageSize value, the response can - include a partial list and a caller should only rely on - response's - [nextPageToken][google.cloud.gkemulticloud.v1.ListAwsNodePoolsResponse.next_page_token] - to determine if there are more instances left to be queried. - page_token (str): - The ``nextPageToken`` value returned from a previous - [awsNodePools.list][google.cloud.gkemulticloud.v1.AwsClusters.ListAwsNodePools] - request, if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAwsNodePoolsResponse(proto.Message): - r"""Response message for ``AwsClusters.ListAwsNodePools`` method. - - Attributes: - aws_node_pools (MutableSequence[google.cloud.gke_multicloud_v1.types.AwsNodePool]): - A list of - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resources in the specified ``AwsCluster``. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - aws_node_pools: MutableSequence[aws_resources.AwsNodePool] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=aws_resources.AwsNodePool, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteAwsNodePoolRequest(proto.Message): - r"""Request message for ``AwsClusters.DeleteAwsNodePool`` method. - - Attributes: - name (str): - Required. The resource name the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] to - delete. - - ``AwsNodePool`` names are formatted as - ``projects//locations//awsClusters//awsNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - validate_only (bool): - If set, only validate the request, but do not - actually delete the node pool. - allow_missing (bool): - If set to true, and the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource is not found, the request will succeed but no - action will be taken on the server and a completed - [Operation][google.longrunning.Operation] will be returned. - - Useful for idempotent deletion. - ignore_errors (bool): - Optional. If set to true, the deletion of - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] - resource will succeed even if errors occur during deleting - in node pool resources. Using this parameter may result in - orphaned resources in the node pool. - etag (str): - The current ETag of the - [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. - - Allows clients to perform deletions through optimistic - concurrency control. - - If the provided ETag does not match the current etag of the - node pool, the request will fail and an ABORTED error will - be returned. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - ignore_errors: bool = proto.Field( - proto.BOOL, - number=5, - ) - etag: str = proto.Field( - proto.STRING, - number=4, - ) - - -class GetAwsOpenIdConfigRequest(proto.Message): - r"""GetAwsOpenIdConfigRequest gets the OIDC discovery document - for the cluster. See the OpenID Connect Discovery 1.0 - specification for details. - - Attributes: - aws_cluster (str): - Required. The AwsCluster, which owns the OIDC - discovery document. Format: - - projects/{project}/locations/{location}/awsClusters/{cluster} - """ - - aws_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetAwsJsonWebKeysRequest(proto.Message): - r"""GetAwsJsonWebKeysRequest gets the public component of the keys used - by the cluster to sign token requests. This will be the jwks_uri for - the discover document returned by getOpenIDConfig. See the OpenID - Connect Discovery 1.0 specification for details. - - Attributes: - aws_cluster (str): - Required. The AwsCluster, which owns the - JsonWebKeys. Format: - - projects/{project}/locations/{location}/awsClusters/{cluster} - """ - - aws_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetAwsServerConfigRequest(proto.Message): - r"""GetAwsServerConfigRequest gets the server config of GKE - cluster on AWS. - - Attributes: - name (str): - Required. The name of the - [AwsServerConfig][google.cloud.gkemulticloud.v1.AwsServerConfig] - resource to describe. - - ``AwsServerConfig`` names are formatted as - ``projects//locations//awsServerConfig``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateAwsAccessTokenRequest(proto.Message): - r"""Request message for ``AwsClusters.GenerateAwsAccessToken`` method. - - Attributes: - aws_cluster (str): - Required. The name of the - [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] - resource to authenticate to. - - ``AwsCluster`` names are formatted as - ``projects//locations//awsClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - """ - - aws_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateAwsAccessTokenResponse(proto.Message): - r"""Response message for ``AwsClusters.GenerateAwsAccessToken`` method. - - Attributes: - access_token (str): - Output only. Access token to authenticate to - k8s api-server. - expiration_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp at which the token - will expire. - """ - - access_token: str = proto.Field( - proto.STRING, - number=1, - ) - expiration_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class GenerateAwsClusterAgentTokenRequest(proto.Message): - r""" - - Attributes: - aws_cluster (str): - Required. - subject_token (str): - Required. - subject_token_type (str): - Required. - version (str): - Required. - node_pool_id (str): - Optional. - grant_type (str): - Optional. - audience (str): - Optional. - scope (str): - Optional. - requested_token_type (str): - Optional. - options (str): - Optional. - """ - - aws_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - subject_token: str = proto.Field( - proto.STRING, - number=2, - ) - subject_token_type: str = proto.Field( - proto.STRING, - number=3, - ) - version: str = proto.Field( - proto.STRING, - number=4, - ) - node_pool_id: str = proto.Field( - proto.STRING, - number=5, - ) - grant_type: str = proto.Field( - proto.STRING, - number=6, - ) - audience: str = proto.Field( - proto.STRING, - number=7, - ) - scope: str = proto.Field( - proto.STRING, - number=8, - ) - requested_token_type: str = proto.Field( - proto.STRING, - number=9, - ) - options: str = proto.Field( - proto.STRING, - number=10, - ) - - -class GenerateAwsClusterAgentTokenResponse(proto.Message): - r""" - - Attributes: - access_token (str): - - expires_in (int): - - token_type (str): - - """ - - access_token: str = proto.Field( - proto.STRING, - number=1, - ) - expires_in: int = proto.Field( - proto.INT32, - number=2, - ) - token_type: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_resources.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_resources.py deleted file mode 100644 index 93a31f553c69..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_resources.py +++ /dev/null @@ -1,1398 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.gke_multicloud_v1.types import common_resources -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.gkemulticloud.v1', - manifest={ - 'AzureCluster', - 'AzureClusterNetworking', - 'AzureControlPlane', - 'ReplicaPlacement', - 'AzureProxyConfig', - 'AzureDatabaseEncryption', - 'AzureConfigEncryption', - 'AzureDiskTemplate', - 'AzureClient', - 'AzureAuthorization', - 'AzureServicesAuthentication', - 'AzureClusterUser', - 'AzureClusterGroup', - 'AzureNodePool', - 'AzureNodeManagement', - 'AzureNodeConfig', - 'AzureNodePoolAutoscaling', - 'AzureOpenIdConfig', - 'AzureJsonWebKeys', - 'AzureServerConfig', - 'AzureK8sVersionInfo', - 'AzureSshConfig', - 'AzureClusterResources', - 'AzureClusterError', - 'AzureNodePoolError', - }, -) - - -class AzureCluster(proto.Message): - r"""An Anthos cluster running on Azure. - - Attributes: - name (str): - The name of this resource. - - Cluster names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - description (str): - Optional. A human readable description of - this cluster. Cannot be longer than 255 UTF-8 - encoded bytes. - azure_region (str): - Required. The Azure region where the cluster runs. - - Each Google Cloud region supports a subset of nearby Azure - regions. You can call - [GetAzureServerConfig][google.cloud.gkemulticloud.v1.AzureClusters.GetAzureServerConfig] - to list all supported Azure regions within a given Google - Cloud region. - resource_group_id (str): - Required. The ARM ID of the resource group where the cluster - resources are deployed. For example: - ``/subscriptions//resourceGroups/`` - azure_client (str): - Optional. Name of the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - that contains authentication configuration for how the - Anthos Multi-Cloud API connects to Azure APIs. - - Either azure_client or azure_services_authentication should - be provided. - - The ``AzureClient`` resource must reside on the same Google - Cloud Platform project and region as the ``AzureCluster``. - - ``AzureClient`` names are formatted as - ``projects//locations//azureClients/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - networking (google.cloud.gke_multicloud_v1.types.AzureClusterNetworking): - Required. Cluster-wide networking - configuration. - control_plane (google.cloud.gke_multicloud_v1.types.AzureControlPlane): - Required. Configuration related to the - cluster control plane. - authorization (google.cloud.gke_multicloud_v1.types.AzureAuthorization): - Required. Configuration related to the - cluster RBAC settings. - azure_services_authentication (google.cloud.gke_multicloud_v1.types.AzureServicesAuthentication): - Optional. Authentication configuration for management of - Azure resources. - - Either azure_client or azure_services_authentication should - be provided. - state (google.cloud.gke_multicloud_v1.types.AzureCluster.State): - Output only. The current state of the - cluster. - endpoint (str): - Output only. The endpoint of the cluster's - API server. - uid (str): - Output only. A globally unique identifier for - the cluster. - reconciling (bool): - Output only. If set, there are currently - changes in flight to the cluster. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this cluster - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this cluster - was last updated. - etag (str): - Allows clients to perform consistent - read-modify-writes through optimistic - concurrency control. - - Can be sent on update and delete requests to - ensure the client has an up-to-date value before - proceeding. - annotations (MutableMapping[str, str]): - Optional. Annotations on the cluster. - - This field has the same restrictions as Kubernetes - annotations. The total size of all keys and values combined - is limited to 256k. Keys can have 2 segments: prefix - (optional) and name (required), separated by a slash (/). - Prefix must be a DNS subdomain. Name must be 63 characters - or less, begin and end with alphanumerics, with dashes (-), - underscores (_), dots (.), and alphanumerics between. - workload_identity_config (google.cloud.gke_multicloud_v1.types.WorkloadIdentityConfig): - Output only. Workload Identity settings. - cluster_ca_certificate (str): - Output only. PEM encoded x509 certificate of - the cluster root of trust. - fleet (google.cloud.gke_multicloud_v1.types.Fleet): - Required. Fleet configuration. - managed_resources (google.cloud.gke_multicloud_v1.types.AzureClusterResources): - Output only. Managed Azure resources for this - cluster. - logging_config (google.cloud.gke_multicloud_v1.types.LoggingConfig): - Optional. Logging configuration for this - cluster. - errors (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureClusterError]): - Output only. A set of errors found in the - cluster. - monitoring_config (google.cloud.gke_multicloud_v1.types.MonitoringConfig): - Optional. Monitoring configuration for this - cluster. - """ - class State(proto.Enum): - r"""The lifecycle state of the cluster. - - Values: - STATE_UNSPECIFIED (0): - Not set. - PROVISIONING (1): - The PROVISIONING state indicates the cluster - is being created. - RUNNING (2): - The RUNNING state indicates the cluster has - been created and is fully usable. - RECONCILING (3): - The RECONCILING state indicates that some - work is actively being done on the cluster, such - as upgrading the control plane replicas. - STOPPING (4): - The STOPPING state indicates the cluster is - being deleted. - ERROR (5): - The ERROR state indicates the cluster is in a - broken unrecoverable state. - DEGRADED (6): - The DEGRADED state indicates the cluster - requires user action to restore full - functionality. - """ - STATE_UNSPECIFIED = 0 - PROVISIONING = 1 - RUNNING = 2 - RECONCILING = 3 - STOPPING = 4 - ERROR = 5 - DEGRADED = 6 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - azure_region: str = proto.Field( - proto.STRING, - number=3, - ) - resource_group_id: str = proto.Field( - proto.STRING, - number=17, - ) - azure_client: str = proto.Field( - proto.STRING, - number=16, - ) - networking: 'AzureClusterNetworking' = proto.Field( - proto.MESSAGE, - number=4, - message='AzureClusterNetworking', - ) - control_plane: 'AzureControlPlane' = proto.Field( - proto.MESSAGE, - number=5, - message='AzureControlPlane', - ) - authorization: 'AzureAuthorization' = proto.Field( - proto.MESSAGE, - number=6, - message='AzureAuthorization', - ) - azure_services_authentication: 'AzureServicesAuthentication' = proto.Field( - proto.MESSAGE, - number=22, - message='AzureServicesAuthentication', - ) - state: State = proto.Field( - proto.ENUM, - number=7, - enum=State, - ) - endpoint: str = proto.Field( - proto.STRING, - number=8, - ) - uid: str = proto.Field( - proto.STRING, - number=9, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=10, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=13, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=14, - ) - workload_identity_config: common_resources.WorkloadIdentityConfig = proto.Field( - proto.MESSAGE, - number=18, - message=common_resources.WorkloadIdentityConfig, - ) - cluster_ca_certificate: str = proto.Field( - proto.STRING, - number=19, - ) - fleet: common_resources.Fleet = proto.Field( - proto.MESSAGE, - number=20, - message=common_resources.Fleet, - ) - managed_resources: 'AzureClusterResources' = proto.Field( - proto.MESSAGE, - number=21, - message='AzureClusterResources', - ) - logging_config: common_resources.LoggingConfig = proto.Field( - proto.MESSAGE, - number=23, - message=common_resources.LoggingConfig, - ) - errors: MutableSequence['AzureClusterError'] = proto.RepeatedField( - proto.MESSAGE, - number=24, - message='AzureClusterError', - ) - monitoring_config: common_resources.MonitoringConfig = proto.Field( - proto.MESSAGE, - number=25, - message=common_resources.MonitoringConfig, - ) - - -class AzureClusterNetworking(proto.Message): - r"""ClusterNetworking contains cluster-wide networking - configuration. - - Attributes: - virtual_network_id (str): - Required. The Azure Resource Manager (ARM) ID of the VNet - associated with your cluster. - - All components in the cluster (i.e. control plane and node - pools) run on a single VNet. - - Example: - ``/subscriptions//resourceGroups//providers/Microsoft.Network/virtualNetworks/`` - - This field cannot be changed after creation. - pod_address_cidr_blocks (MutableSequence[str]): - Required. The IP address range of the pods in this cluster, - in CIDR notation (e.g. ``10.96.0.0/14``). - - All pods in the cluster get assigned a unique IPv4 address - from these ranges. Only a single range is supported. - - This field cannot be changed after creation. - service_address_cidr_blocks (MutableSequence[str]): - Required. The IP address range for services in this cluster, - in CIDR notation (e.g. ``10.96.0.0/14``). - - All services in the cluster get assigned a unique IPv4 - address from these ranges. Only a single range is supported. - - This field cannot be changed after creating a cluster. - service_load_balancer_subnet_id (str): - Optional. The ARM ID of the subnet where Kubernetes private - service type load balancers are deployed. When unspecified, - it defaults to AzureControlPlane.subnet_id. - - Example: - "/subscriptions/d00494d6-6f3c-4280-bbb2-899e163d1d30/resourceGroups/anthos_cluster_gkeust4/providers/Microsoft.Network/virtualNetworks/gke-vnet-gkeust4/subnets/subnetid456". - """ - - virtual_network_id: str = proto.Field( - proto.STRING, - number=1, - ) - pod_address_cidr_blocks: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - service_address_cidr_blocks: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - service_load_balancer_subnet_id: str = proto.Field( - proto.STRING, - number=5, - ) - - -class AzureControlPlane(proto.Message): - r"""AzureControlPlane represents the control plane - configurations. - - Attributes: - version (str): - Required. The Kubernetes version to run on control plane - replicas (e.g. ``1.19.10-gke.1000``). - - You can list all supported versions on a given Google Cloud - region by calling - [GetAzureServerConfig][google.cloud.gkemulticloud.v1.AzureClusters.GetAzureServerConfig]. - subnet_id (str): - Optional. The ARM ID of the default subnet for the control - plane. The control plane VMs are deployed in this subnet, - unless ``AzureControlPlane.replica_placements`` is - specified. This subnet will also be used as default for - ``AzureControlPlane.endpoint_subnet_id`` if - ``AzureControlPlane.endpoint_subnet_id`` is not specified. - Similarly it will be used as default for - ``AzureClusterNetworking.service_load_balancer_subnet_id``. - - Example: - ``/subscriptions//resourceGroups//providers/Microsoft.Network/virtualNetworks//subnets/default``. - vm_size (str): - Optional. The Azure VM size name. Example: - ``Standard_DS2_v2``. - - For available VM sizes, see - https://docs.microsoft.com/en-us/azure/virtual-machines/vm-naming-conventions. - - When unspecified, it defaults to ``Standard_DS2_v2``. - ssh_config (google.cloud.gke_multicloud_v1.types.AzureSshConfig): - Required. SSH configuration for how to access - the underlying control plane machines. - root_volume (google.cloud.gke_multicloud_v1.types.AzureDiskTemplate): - Optional. Configuration related to the root - volume provisioned for each control plane - replica. - - When unspecified, it defaults to 32-GiB Azure - Disk. - main_volume (google.cloud.gke_multicloud_v1.types.AzureDiskTemplate): - Optional. Configuration related to the main - volume provisioned for each control plane - replica. The main volume is in charge of storing - all of the cluster's etcd state. - - When unspecified, it defaults to a 8-GiB Azure - Disk. - database_encryption (google.cloud.gke_multicloud_v1.types.AzureDatabaseEncryption): - Optional. Configuration related to - application-layer secrets encryption. - proxy_config (google.cloud.gke_multicloud_v1.types.AzureProxyConfig): - Optional. Proxy configuration for outbound - HTTP(S) traffic. - config_encryption (google.cloud.gke_multicloud_v1.types.AzureConfigEncryption): - Optional. Configuration related to vm config - encryption. - tags (MutableMapping[str, str]): - Optional. A set of tags to apply to all - underlying control plane Azure resources. - replica_placements (MutableSequence[google.cloud.gke_multicloud_v1.types.ReplicaPlacement]): - Optional. Configuration for where to place the control plane - replicas. - - Up to three replica placement instances can be specified. If - replica_placements is set, the replica placement instances - will be applied to the three control plane replicas as - evenly as possible. - endpoint_subnet_id (str): - Optional. The ARM ID of the subnet where the control plane - load balancer is deployed. When unspecified, it defaults to - AzureControlPlane.subnet_id. - - Example: - "/subscriptions/d00494d6-6f3c-4280-bbb2-899e163d1d30/resourceGroups/anthos_cluster_gkeust4/providers/Microsoft.Network/virtualNetworks/gke-vnet-gkeust4/subnets/subnetid123". - """ - - version: str = proto.Field( - proto.STRING, - number=1, - ) - subnet_id: str = proto.Field( - proto.STRING, - number=2, - ) - vm_size: str = proto.Field( - proto.STRING, - number=3, - ) - ssh_config: 'AzureSshConfig' = proto.Field( - proto.MESSAGE, - number=11, - message='AzureSshConfig', - ) - root_volume: 'AzureDiskTemplate' = proto.Field( - proto.MESSAGE, - number=4, - message='AzureDiskTemplate', - ) - main_volume: 'AzureDiskTemplate' = proto.Field( - proto.MESSAGE, - number=5, - message='AzureDiskTemplate', - ) - database_encryption: 'AzureDatabaseEncryption' = proto.Field( - proto.MESSAGE, - number=10, - message='AzureDatabaseEncryption', - ) - proxy_config: 'AzureProxyConfig' = proto.Field( - proto.MESSAGE, - number=12, - message='AzureProxyConfig', - ) - config_encryption: 'AzureConfigEncryption' = proto.Field( - proto.MESSAGE, - number=14, - message='AzureConfigEncryption', - ) - tags: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - replica_placements: MutableSequence['ReplicaPlacement'] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message='ReplicaPlacement', - ) - endpoint_subnet_id: str = proto.Field( - proto.STRING, - number=15, - ) - - -class ReplicaPlacement(proto.Message): - r"""Configuration for the placement of a control plane replica. - - Attributes: - subnet_id (str): - Required. For a given replica, the ARM ID of - the subnet where the control plane VM is - deployed. Make sure it's a subnet under the - virtual network in the cluster configuration. - azure_availability_zone (str): - Required. For a given replica, the Azure - availability zone where to provision the control - plane VM and the ETCD disk. - """ - - subnet_id: str = proto.Field( - proto.STRING, - number=1, - ) - azure_availability_zone: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AzureProxyConfig(proto.Message): - r"""Details of a proxy config stored in Azure Key Vault. - - Attributes: - resource_group_id (str): - The ARM ID the of the resource group containing proxy - keyvault. - - Resource group ids are formatted as - ``/subscriptions//resourceGroups/``. - secret_id (str): - The URL the of the proxy setting secret with its version. - - The secret must be a JSON encoded proxy configuration as - described in - https://cloud.google.com/kubernetes-engine/multi-cloud/docs/azure/how-to/use-a-proxy#create_a_proxy_configuration_file - - Secret ids are formatted as - ``https://.vault.azure.net/secrets//``. - """ - - resource_group_id: str = proto.Field( - proto.STRING, - number=1, - ) - secret_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AzureDatabaseEncryption(proto.Message): - r"""Configuration related to application-layer secrets - encryption. - Anthos clusters on Azure encrypts your Kubernetes data at rest - in etcd using Azure Key Vault. - - Attributes: - key_id (str): - Required. The ARM ID of the Azure Key Vault key to encrypt / - decrypt data. - - For example: - ``/subscriptions//resourceGroups//providers/Microsoft.KeyVault/vaults//keys/`` - Encryption will always take the latest version of the key - and hence specific version is not supported. - """ - - key_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class AzureConfigEncryption(proto.Message): - r"""Configuration related to config data encryption. - - Azure VM bootstrap secret is envelope encrypted with the - provided key vault key. - - Attributes: - key_id (str): - Required. The ARM ID of the Azure Key Vault key to encrypt / - decrypt config data. - - For example: - ``/subscriptions//resourceGroups//providers/Microsoft.KeyVault/vaults//keys/`` - public_key (str): - Optional. RSA key of the Azure Key Vault - public key to use for encrypting the data. - - This key must be formatted as a PEM-encoded - SubjectPublicKeyInfo (RFC 5280) in ASN.1 DER - form. The string must be comprised of a single - PEM block of type "PUBLIC KEY". - """ - - key_id: str = proto.Field( - proto.STRING, - number=2, - ) - public_key: str = proto.Field( - proto.STRING, - number=3, - ) - - -class AzureDiskTemplate(proto.Message): - r"""Configuration for Azure Disks. - - Attributes: - size_gib (int): - Optional. The size of the disk, in GiBs. - - When unspecified, a default value is provided. - See the specific reference in the parent - resource. - """ - - size_gib: int = proto.Field( - proto.INT32, - number=1, - ) - - -class AzureClient(proto.Message): - r"""``AzureClient`` resources hold client authentication information - needed by the Anthos Multi-Cloud API to manage Azure resources on - your Azure subscription. - - When an [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - is created, an ``AzureClient`` resource needs to be provided and all - operations on Azure resources associated to that cluster will - authenticate to Azure services using the given client. - - ``AzureClient`` resources are immutable and cannot be modified upon - creation. - - Each ``AzureClient`` resource is bound to a single Azure Active - Directory Application and tenant. - - Attributes: - name (str): - The name of this resource. - - ``AzureClient`` resource names are formatted as - ``projects//locations//azureClients/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - tenant_id (str): - Required. The Azure Active Directory Tenant - ID. - application_id (str): - Required. The Azure Active Directory - Application ID. - reconciling (bool): - Output only. If set, there are currently - pending changes to the client. - annotations (MutableMapping[str, str]): - Optional. Annotations on the resource. - - This field has the same restrictions as Kubernetes - annotations. The total size of all keys and values combined - is limited to 256k. Keys can have 2 segments: prefix - (optional) and name (required), separated by a slash (/). - Prefix must be a DNS subdomain. Name must be 63 characters - or less, begin and end with alphanumerics, with dashes (-), - underscores (_), dots (.), and alphanumerics between. - pem_certificate (str): - Output only. The PEM encoded x509 - certificate. - uid (str): - Output only. A globally unique identifier for - the client. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this resource - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this client - was last updated. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - tenant_id: str = proto.Field( - proto.STRING, - number=2, - ) - application_id: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=9, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - pem_certificate: str = proto.Field( - proto.STRING, - number=7, - ) - uid: str = proto.Field( - proto.STRING, - number=5, - ) - 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=10, - message=timestamp_pb2.Timestamp, - ) - - -class AzureAuthorization(proto.Message): - r"""Configuration related to the cluster RBAC settings. - - Attributes: - admin_users (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureClusterUser]): - Optional. Users that can perform operations as a cluster - admin. A managed ClusterRoleBinding will be created to grant - the ``cluster-admin`` ClusterRole to the users. Up to ten - admin users can be provided. - - For more info on RBAC, see - https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles - admin_groups (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureClusterGroup]): - Optional. Groups of users that can perform operations as a - cluster admin. A managed ClusterRoleBinding will be created - to grant the ``cluster-admin`` ClusterRole to the groups. Up - to ten admin groups can be provided. - - For more info on RBAC, see - https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles - """ - - admin_users: MutableSequence['AzureClusterUser'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AzureClusterUser', - ) - admin_groups: MutableSequence['AzureClusterGroup'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AzureClusterGroup', - ) - - -class AzureServicesAuthentication(proto.Message): - r"""Authentication configuration for the management of Azure - resources. - - Attributes: - tenant_id (str): - Required. The Azure Active Directory Tenant - ID. - application_id (str): - Required. The Azure Active Directory - Application ID. - """ - - tenant_id: str = proto.Field( - proto.STRING, - number=1, - ) - application_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AzureClusterUser(proto.Message): - r"""Identities of a user-type subject for Azure clusters. - - Attributes: - username (str): - Required. The name of the user, e.g. - ``my-gcp-id@gmail.com``. - """ - - username: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AzureClusterGroup(proto.Message): - r"""Identities of a group-type subject for Azure clusters. - - Attributes: - group (str): - Required. The name of the group, e.g. - ``my-group@domain.com``. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AzureNodePool(proto.Message): - r"""An Anthos node pool running on Azure. - - Attributes: - name (str): - The name of this resource. - - Node pool names are formatted as - ``projects//locations//azureClusters//azureNodePools/``. - - For more details on Google Cloud resource names, see - `Resource - Names `__ - version (str): - Required. The Kubernetes version (e.g. ``1.19.10-gke.1000``) - running on this node pool. - config (google.cloud.gke_multicloud_v1.types.AzureNodeConfig): - Required. The node configuration of the node - pool. - subnet_id (str): - Required. The ARM ID of the subnet where the - node pool VMs run. Make sure it's a subnet under - the virtual network in the cluster - configuration. - autoscaling (google.cloud.gke_multicloud_v1.types.AzureNodePoolAutoscaling): - Required. Autoscaler configuration for this - node pool. - state (google.cloud.gke_multicloud_v1.types.AzureNodePool.State): - Output only. The current state of the node - pool. - uid (str): - Output only. A globally unique identifier for - the node pool. - reconciling (bool): - Output only. If set, there are currently - pending changes to the node pool. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this node pool - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this node pool - was last updated. - etag (str): - Allows clients to perform consistent - read-modify-writes through optimistic - concurrency control. - - Can be sent on update and delete requests to - ensure the client has an up-to-date value before - proceeding. - annotations (MutableMapping[str, str]): - Optional. Annotations on the node pool. - - This field has the same restrictions as Kubernetes - annotations. The total size of all keys and values combined - is limited to 256k. Keys can have 2 segments: prefix - (optional) and name (required), separated by a slash (/). - Prefix must be a DNS subdomain. Name must be 63 characters - or less, begin and end with alphanumerics, with dashes (-), - underscores (_), dots (.), and alphanumerics between. - max_pods_constraint (google.cloud.gke_multicloud_v1.types.MaxPodsConstraint): - Required. The constraint on the maximum - number of pods that can be run simultaneously on - a node in the node pool. - azure_availability_zone (str): - Optional. The Azure availability zone of the nodes in this - nodepool. - - When unspecified, it defaults to ``1``. - errors (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureNodePoolError]): - Output only. A set of errors found in the - node pool. - management (google.cloud.gke_multicloud_v1.types.AzureNodeManagement): - Optional. The Management configuration for - this node pool. - """ - class State(proto.Enum): - r"""The lifecycle state of the node pool. - - Values: - STATE_UNSPECIFIED (0): - Not set. - PROVISIONING (1): - The PROVISIONING state indicates the node - pool is being created. - RUNNING (2): - The RUNNING state indicates the node pool has - been created and is fully usable. - RECONCILING (3): - The RECONCILING state indicates that the node - pool is being reconciled. - STOPPING (4): - The STOPPING state indicates the node pool is - being deleted. - ERROR (5): - The ERROR state indicates the node pool is in - a broken unrecoverable state. - DEGRADED (6): - The DEGRADED state indicates the node pool - requires user action to restore full - functionality. - """ - STATE_UNSPECIFIED = 0 - PROVISIONING = 1 - RUNNING = 2 - RECONCILING = 3 - STOPPING = 4 - ERROR = 5 - DEGRADED = 6 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - config: 'AzureNodeConfig' = proto.Field( - proto.MESSAGE, - number=22, - message='AzureNodeConfig', - ) - subnet_id: str = proto.Field( - proto.STRING, - number=3, - ) - autoscaling: 'AzureNodePoolAutoscaling' = proto.Field( - proto.MESSAGE, - number=4, - message='AzureNodePoolAutoscaling', - ) - state: State = proto.Field( - proto.ENUM, - number=6, - enum=State, - ) - uid: str = proto.Field( - proto.STRING, - number=8, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=9, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=12, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=13, - ) - max_pods_constraint: common_resources.MaxPodsConstraint = proto.Field( - proto.MESSAGE, - number=21, - message=common_resources.MaxPodsConstraint, - ) - azure_availability_zone: str = proto.Field( - proto.STRING, - number=23, - ) - errors: MutableSequence['AzureNodePoolError'] = proto.RepeatedField( - proto.MESSAGE, - number=29, - message='AzureNodePoolError', - ) - management: 'AzureNodeManagement' = proto.Field( - proto.MESSAGE, - number=30, - message='AzureNodeManagement', - ) - - -class AzureNodeManagement(proto.Message): - r"""AzureNodeManagement defines the set of node management - features turned on for an Azure node pool. - - Attributes: - auto_repair (bool): - Optional. Whether or not the nodes will be - automatically repaired. When set to true, the - nodes in this node pool will be monitored and if - they fail health checks consistently over a - period of time, an automatic repair action will - be triggered to replace them with new nodes. - """ - - auto_repair: bool = proto.Field( - proto.BOOL, - number=1, - ) - - -class AzureNodeConfig(proto.Message): - r"""Parameters that describe the configuration of all node - machines on a given node pool. - - Attributes: - vm_size (str): - Optional. The Azure VM size name. Example: - ``Standard_DS2_v2``. - - See `Supported VM - sizes `__ - for options. - - When unspecified, it defaults to ``Standard_DS2_v2``. - root_volume (google.cloud.gke_multicloud_v1.types.AzureDiskTemplate): - Optional. Configuration related to the root - volume provisioned for each node pool machine. - - When unspecified, it defaults to a 32-GiB Azure - Disk. - tags (MutableMapping[str, str]): - Optional. A set of tags to apply to all underlying Azure - resources for this node pool. This currently only includes - Virtual Machine Scale Sets. - - Specify at most 50 pairs containing alphanumerics, spaces, - and symbols (.+-=_:@/). Keys can be up to 127 Unicode - characters. Values can be up to 255 Unicode characters. - image_type (str): - Optional. The OS image type to use on node pool instances. - Can be unspecified, or have a value of ``ubuntu``. - - When unspecified, it defaults to ``ubuntu``. - ssh_config (google.cloud.gke_multicloud_v1.types.AzureSshConfig): - Required. SSH configuration for how to access - the node pool machines. - proxy_config (google.cloud.gke_multicloud_v1.types.AzureProxyConfig): - Optional. Proxy configuration for outbound - HTTP(S) traffic. - config_encryption (google.cloud.gke_multicloud_v1.types.AzureConfigEncryption): - Optional. Configuration related to vm config - encryption. - taints (MutableSequence[google.cloud.gke_multicloud_v1.types.NodeTaint]): - Optional. The initial taints assigned to - nodes of this node pool. - labels (MutableMapping[str, str]): - Optional. The initial labels assigned to - nodes of this node pool. An object containing a - list of "key": value pairs. Example: { "name": - "wrench", "mass": "1.3kg", "count": "3" }. - """ - - vm_size: str = proto.Field( - proto.STRING, - number=1, - ) - root_volume: 'AzureDiskTemplate' = proto.Field( - proto.MESSAGE, - number=2, - message='AzureDiskTemplate', - ) - tags: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - image_type: str = proto.Field( - proto.STRING, - number=8, - ) - ssh_config: 'AzureSshConfig' = proto.Field( - proto.MESSAGE, - number=7, - message='AzureSshConfig', - ) - proxy_config: 'AzureProxyConfig' = proto.Field( - proto.MESSAGE, - number=9, - message='AzureProxyConfig', - ) - config_encryption: 'AzureConfigEncryption' = proto.Field( - proto.MESSAGE, - number=12, - message='AzureConfigEncryption', - ) - taints: MutableSequence[common_resources.NodeTaint] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=common_resources.NodeTaint, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=11, - ) - - -class AzureNodePoolAutoscaling(proto.Message): - r"""Configuration related to Kubernetes cluster autoscaler. - - The Kubernetes cluster autoscaler will automatically adjust the - size of the node pool based on the cluster load. - - Attributes: - min_node_count (int): - Required. Minimum number of nodes in the node pool. Must be - greater than or equal to 1 and less than or equal to - max_node_count. - max_node_count (int): - Required. Maximum number of nodes in the node pool. Must be - greater than or equal to min_node_count and less than or - equal to 50. - """ - - min_node_count: int = proto.Field( - proto.INT32, - number=1, - ) - max_node_count: int = proto.Field( - proto.INT32, - number=2, - ) - - -class AzureOpenIdConfig(proto.Message): - r"""AzureOpenIdConfig is an OIDC discovery document for the - cluster. See the OpenID Connect Discovery 1.0 specification for - details. - - Attributes: - issuer (str): - OIDC Issuer. - jwks_uri (str): - JSON Web Key uri. - response_types_supported (MutableSequence[str]): - Supported response types. - subject_types_supported (MutableSequence[str]): - Supported subject types. - id_token_signing_alg_values_supported (MutableSequence[str]): - supported ID Token signing Algorithms. - claims_supported (MutableSequence[str]): - Supported claims. - grant_types (MutableSequence[str]): - Supported grant types. - """ - - issuer: str = proto.Field( - proto.STRING, - number=1, - ) - jwks_uri: str = proto.Field( - proto.STRING, - number=2, - ) - response_types_supported: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - subject_types_supported: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - id_token_signing_alg_values_supported: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - claims_supported: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - grant_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - - -class AzureJsonWebKeys(proto.Message): - r"""AzureJsonWebKeys is a valid JSON Web Key Set as specififed in - RFC 7517. - - Attributes: - keys (MutableSequence[google.cloud.gke_multicloud_v1.types.Jwk]): - The public component of the keys used by the - cluster to sign token requests. - """ - - keys: MutableSequence[common_resources.Jwk] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=common_resources.Jwk, - ) - - -class AzureServerConfig(proto.Message): - r"""AzureServerConfig contains information about a Google Cloud - location, such as supported Azure regions and Kubernetes - versions. - - Attributes: - name (str): - The ``AzureServerConfig`` resource name. - - ``AzureServerConfig`` names are formatted as - ``projects//locations//azureServerConfig``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - valid_versions (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureK8sVersionInfo]): - List of all released Kubernetes versions, including ones - which are end of life and can no longer be used. Filter by - the ``enabled`` property to limit to currently available - versions. Valid versions supported for both create and - update operations - supported_azure_regions (MutableSequence[str]): - The list of supported Azure regions. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - valid_versions: MutableSequence['AzureK8sVersionInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AzureK8sVersionInfo', - ) - supported_azure_regions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class AzureK8sVersionInfo(proto.Message): - r"""Kubernetes version information of GKE cluster on Azure. - - Attributes: - version (str): - Kubernetes version name (for example, ``1.19.10-gke.1000``) - enabled (bool): - Optional. True if the version is available - for cluster creation. If a version is enabled - for creation, it can be used to create new - clusters. Otherwise, cluster creation will fail. - However, cluster upgrade operations may succeed, - even if the version is not enabled. - end_of_life (bool): - Optional. True if this cluster version - belongs to a minor version that has reached its - end of life and is no longer in scope to receive - security and bug fixes. - end_of_life_date (google.type.date_pb2.Date): - Optional. The estimated date (in Pacific Time) when this - cluster version will reach its end of life. Or if this - version is no longer supported (the ``end_of_life`` field is - true), this is the actual date (in Pacific time) when the - version reached its end of life. - release_date (google.type.date_pb2.Date): - Optional. The date (in Pacific Time) when the - cluster version was released. - """ - - version: str = proto.Field( - proto.STRING, - number=1, - ) - enabled: bool = proto.Field( - proto.BOOL, - number=3, - ) - end_of_life: bool = proto.Field( - proto.BOOL, - number=4, - ) - end_of_life_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=5, - message=date_pb2.Date, - ) - release_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=6, - message=date_pb2.Date, - ) - - -class AzureSshConfig(proto.Message): - r"""SSH configuration for Azure resources. - - Attributes: - authorized_key (str): - Required. The SSH public key data for VMs managed by Anthos. - This accepts the authorized_keys file format used in OpenSSH - according to the sshd(8) manual page. - """ - - authorized_key: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AzureClusterResources(proto.Message): - r"""Managed Azure resources for the cluster. - - The values could change and be empty, depending on the state of - the cluster. - - Attributes: - network_security_group_id (str): - Output only. The ARM ID of the cluster - network security group. - control_plane_application_security_group_id (str): - Output only. The ARM ID of the control plane - application security group. - """ - - network_security_group_id: str = proto.Field( - proto.STRING, - number=1, - ) - control_plane_application_security_group_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AzureClusterError(proto.Message): - r"""AzureClusterError describes errors found on Azure clusters. - - Attributes: - message (str): - Human-friendly description of the error. - """ - - message: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AzureNodePoolError(proto.Message): - r"""AzureNodePoolError describes errors found on Azure node - pools. - - Attributes: - message (str): - Human-friendly description of the error. - """ - - message: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_service.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_service.py deleted file mode 100644 index 44c9d74a5e84..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/azure_service.py +++ /dev/null @@ -1,986 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.gke_multicloud_v1.types import azure_resources -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.gkemulticloud.v1', - manifest={ - 'CreateAzureClusterRequest', - 'UpdateAzureClusterRequest', - 'GetAzureClusterRequest', - 'ListAzureClustersRequest', - 'ListAzureClustersResponse', - 'DeleteAzureClusterRequest', - 'CreateAzureNodePoolRequest', - 'UpdateAzureNodePoolRequest', - 'GetAzureNodePoolRequest', - 'ListAzureNodePoolsRequest', - 'ListAzureNodePoolsResponse', - 'DeleteAzureNodePoolRequest', - 'GetAzureOpenIdConfigRequest', - 'GetAzureJsonWebKeysRequest', - 'GetAzureServerConfigRequest', - 'CreateAzureClientRequest', - 'GetAzureClientRequest', - 'ListAzureClientsRequest', - 'ListAzureClientsResponse', - 'DeleteAzureClientRequest', - 'GenerateAzureAccessTokenRequest', - 'GenerateAzureAccessTokenResponse', - 'GenerateAzureClusterAgentTokenRequest', - 'GenerateAzureClusterAgentTokenResponse', - }, -) - - -class CreateAzureClusterRequest(proto.Message): - r"""Request message for ``AzureClusters.CreateAzureCluster`` method. - - Attributes: - parent (str): - Required. The parent location where this - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - azure_cluster (google.cloud.gke_multicloud_v1.types.AzureCluster): - Required. The specification of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - to create. - azure_cluster_id (str): - Required. A client provided ID the resource. Must be unique - within the parent resource. - - The provided ID will be part of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource name formatted as - ``projects//locations//azureClusters/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - validate_only (bool): - If set, only validate the request, but do not - actually create the cluster. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - azure_cluster: azure_resources.AzureCluster = proto.Field( - proto.MESSAGE, - number=2, - message=azure_resources.AzureCluster, - ) - azure_cluster_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateAzureClusterRequest(proto.Message): - r"""Request message for ``AzureClusters.UpdateAzureCluster`` method. - - Attributes: - azure_cluster (google.cloud.gke_multicloud_v1.types.AzureCluster): - Required. The - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource to update. - validate_only (bool): - If set, only validate the request, but do not - actually update the cluster. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask of fields to update. At least one path must - be supplied in this field. The elements of the repeated - paths field can only include these fields from - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]: - - - ``description``. - - ``azureClient``. - - ``control_plane.version``. - - ``control_plane.vm_size``. - - ``annotations``. - - ``authorization.admin_users``. - - ``authorization.admin_groups``. - - ``control_plane.root_volume.size_gib``. - - ``azure_services_authentication``. - - ``azure_services_authentication.tenant_id``. - - ``azure_services_authentication.application_id``. - - ``control_plane.proxy_config``. - - ``control_plane.proxy_config.resource_group_id``. - - ``control_plane.proxy_config.secret_id``. - - ``control_plane.ssh_config.authorized_key``. - - ``logging_config.component_config.enable_components`` - - ``monitoring_config.managed_prometheus_config.enabled``. - """ - - azure_cluster: azure_resources.AzureCluster = proto.Field( - proto.MESSAGE, - number=1, - message=azure_resources.AzureCluster, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class GetAzureClusterRequest(proto.Message): - r"""Request message for ``AzureClusters.GetAzureCluster`` method. - - Attributes: - name (str): - Required. The name of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource to describe. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListAzureClustersRequest(proto.Message): - r"""Request message for ``AzureClusters.ListAzureClusters`` method. - - Attributes: - parent (str): - Required. The parent location which owns this collection of - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - page_size (int): - The maximum number of items to return. - - If not specified, a default value of 50 will be used by the - service. Regardless of the pageSize value, the response can - include a partial list and a caller should only rely on - response's - [nextPageToken][google.cloud.gkemulticloud.v1.ListAzureClustersResponse.next_page_token] - to determine if there are more instances left to be queried. - page_token (str): - The ``nextPageToken`` value returned from a previous - [azureClusters.list][google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClusters] - request, if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAzureClustersResponse(proto.Message): - r"""Response message for ``AzureClusters.ListAzureClusters`` method. - - Attributes: - azure_clusters (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureCluster]): - A list of - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resources in the specified Google Cloud Platform project and - region region. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - azure_clusters: MutableSequence[azure_resources.AzureCluster] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=azure_resources.AzureCluster, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteAzureClusterRequest(proto.Message): - r"""Request message for ``AzureClusters.DeleteAzureCluster`` method. - - Attributes: - name (str): - Required. The resource name the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - to delete. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - allow_missing (bool): - If set to true, and the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource is not found, the request will succeed but no - action will be taken on the server and a completed - [Operation][google.longrunning.Operation] will be returned. - - Useful for idempotent deletion. - validate_only (bool): - If set, only validate the request, but do not - actually delete the resource. - etag (str): - The current etag of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. - - Allows clients to perform deletions through optimistic - concurrency control. - - If the provided etag does not match the current etag of the - cluster, the request will fail and an ABORTED error will be - returned. - ignore_errors (bool): - Optional. If set to true, the deletion of - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource will succeed even if errors occur during deleting - in cluster resources. Using this parameter may result in - orphaned resources in the cluster. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=2, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - etag: str = proto.Field( - proto.STRING, - number=4, - ) - ignore_errors: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class CreateAzureNodePoolRequest(proto.Message): - r"""Response message for ``AzureClusters.CreateAzureNodePool`` method. - - Attributes: - parent (str): - Required. The - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource where this node pool will be created. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - azure_node_pool (google.cloud.gke_multicloud_v1.types.AzureNodePool): - Required. The specification of the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - to create. - azure_node_pool_id (str): - Required. A client provided ID the resource. Must be unique - within the parent resource. - - The provided ID will be part of the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource name formatted as - ``projects//locations//azureClusters//azureNodePools/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - validate_only (bool): - If set, only validate the request, but do not - actually create the node pool. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - azure_node_pool: azure_resources.AzureNodePool = proto.Field( - proto.MESSAGE, - number=2, - message=azure_resources.AzureNodePool, - ) - azure_node_pool_id: str = proto.Field( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateAzureNodePoolRequest(proto.Message): - r"""Request message for ``AzureClusters.UpdateAzureNodePool`` method. - - Attributes: - azure_node_pool (google.cloud.gke_multicloud_v1.types.AzureNodePool): - Required. The - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource to update. - validate_only (bool): - If set, only validate the request, but don't - actually update the node pool. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask of fields to update. At least one path must - be supplied in this field. The elements of the repeated - paths field can only include these fields from - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]: - - \*. ``annotations``. - - - ``version``. - - ``autoscaling.min_node_count``. - - ``autoscaling.max_node_count``. - - ``config.ssh_config.authorized_key``. - - ``management.auto_repair``. - - ``management``. - """ - - azure_node_pool: azure_resources.AzureNodePool = proto.Field( - proto.MESSAGE, - number=1, - message=azure_resources.AzureNodePool, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class GetAzureNodePoolRequest(proto.Message): - r"""Request message for ``AzureClusters.GetAzureNodePool`` method. - - Attributes: - name (str): - Required. The name of the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource to describe. - - ``AzureNodePool`` names are formatted as - ``projects//locations//azureClusters//azureNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListAzureNodePoolsRequest(proto.Message): - r"""Request message for ``AzureClusters.ListAzureNodePools`` method. - - Attributes: - parent (str): - Required. The parent ``AzureCluster`` which owns this - collection of - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - page_size (int): - The maximum number of items to return. - - If not specified, a default value of 50 will be used by the - service. Regardless of the pageSize value, the response can - include a partial list and a caller should only rely on - response's - [nextPageToken][google.cloud.gkemulticloud.v1.ListAzureNodePoolsResponse.next_page_token] - to determine if there are more instances left to be queried. - page_token (str): - The ``nextPageToken`` value returned from a previous - [azureNodePools.list][google.cloud.gkemulticloud.v1.AzureClusters.ListAzureNodePools] - request, if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAzureNodePoolsResponse(proto.Message): - r"""Response message for ``AzureClusters.ListAzureNodePools`` method. - - Attributes: - azure_node_pools (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureNodePool]): - A list of - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resources in the specified ``AzureCluster``. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - azure_node_pools: MutableSequence[azure_resources.AzureNodePool] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=azure_resources.AzureNodePool, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteAzureNodePoolRequest(proto.Message): - r"""Request message for ``AzureClusters.DeleteAzureNodePool`` method. - - Attributes: - name (str): - Required. The resource name the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - to delete. - - ``AzureNodePool`` names are formatted as - ``projects//locations//azureClusters//azureNodePools/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - validate_only (bool): - If set, only validate the request, but do not - actually delete the node pool. - allow_missing (bool): - If set to true, and the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource is not found, the request will succeed but no - action will be taken on the server and a completed - [Operation][google.longrunning.Operation] will be returned. - - Useful for idempotent deletion. - etag (str): - The current ETag of the - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. - - Allows clients to perform deletions through optimistic - concurrency control. - - If the provided ETag does not match the current etag of the - node pool, the request will fail and an ABORTED error will - be returned. - ignore_errors (bool): - Optional. If set to true, the deletion of - [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] - resource will succeed even if errors occur during deleting - in node pool resources. Using this parameter may result in - orphaned resources in the node pool. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - etag: str = proto.Field( - proto.STRING, - number=4, - ) - ignore_errors: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class GetAzureOpenIdConfigRequest(proto.Message): - r"""GetAzureOpenIdConfigRequest gets the OIDC discovery document - for the cluster. See the OpenID Connect Discovery 1.0 - specification for details. - - Attributes: - azure_cluster (str): - Required. The AzureCluster, which owns the - OIDC discovery document. Format: - - projects//locations//azureClusters/ - """ - - azure_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetAzureJsonWebKeysRequest(proto.Message): - r"""GetAzureJsonWebKeysRequest gets the public component of the keys - used by the cluster to sign token requests. This will be the - jwks_uri for the discover document returned by getOpenIDConfig. See - the OpenID Connect Discovery 1.0 specification for details. - - Attributes: - azure_cluster (str): - Required. The AzureCluster, which owns the JsonWebKeys. - Format: - ``projects//locations//azureClusters/`` - """ - - azure_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetAzureServerConfigRequest(proto.Message): - r"""GetAzureServerConfigRequest gets the server config of GKE - cluster on Azure. - - Attributes: - name (str): - Required. The name of the - [AzureServerConfig][google.cloud.gkemulticloud.v1.AzureServerConfig] - resource to describe. - - ``AzureServerConfig`` names are formatted as - ``projects//locations//azureServerConfig``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateAzureClientRequest(proto.Message): - r"""Request message for ``AzureClusters.CreateAzureClient`` method. - - Attributes: - parent (str): - Required. The parent location where this - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource will be created. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - azure_client (google.cloud.gke_multicloud_v1.types.AzureClient): - Required. The specification of the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] to - create. - azure_client_id (str): - Required. A client provided ID the resource. Must be unique - within the parent resource. - - The provided ID will be part of the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource name formatted as - ``projects//locations//azureClients/``. - - Valid characters are ``/[a-z][0-9]-/``. Cannot be longer - than 63 characters. - validate_only (bool): - If set, only validate the request, but do not - actually create the client. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - azure_client: azure_resources.AzureClient = proto.Field( - proto.MESSAGE, - number=2, - message=azure_resources.AzureClient, - ) - azure_client_id: str = proto.Field( - proto.STRING, - number=4, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class GetAzureClientRequest(proto.Message): - r"""Request message for ``AzureClusters.GetAzureClient`` method. - - Attributes: - name (str): - Required. The name of the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource to describe. - - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - names are formatted as - ``projects//locations//azureClients/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListAzureClientsRequest(proto.Message): - r"""Request message for ``AzureClusters.ListAzureClients`` method. - - Attributes: - parent (str): - Required. The parent location which owns this collection of - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resources. - - Location names are formatted as - ``projects//locations/``. - - See `Resource - Names `__ - for more details on Google Cloud Platform resource names. - page_size (int): - The maximum number of items to return. - - If not specified, a default value of 50 will be used by the - service. Regardless of the pageSize value, the response can - include a partial list and a caller should only rely on - response's - [nextPageToken][google.cloud.gkemulticloud.v1.ListAzureClientsResponse.next_page_token] - to determine if there are more instances left to be queried. - page_token (str): - The ``nextPageToken`` value returned from a previous - [azureClients.list][google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClients] - request, if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAzureClientsResponse(proto.Message): - r"""Response message for ``AzureClusters.ListAzureClients`` method. - - Attributes: - azure_clients (MutableSequence[google.cloud.gke_multicloud_v1.types.AzureClient]): - A list of - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resources in the specified Google Cloud project and region - region. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - azure_clients: MutableSequence[azure_resources.AzureClient] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=azure_resources.AzureClient, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteAzureClientRequest(proto.Message): - r"""Request message for ``AzureClusters.DeleteAzureClient`` method. - - Attributes: - name (str): - Required. The resource name the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] to - delete. - - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - names are formatted as - ``projects//locations//azureClients/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - allow_missing (bool): - If set to true, and the - [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] - resource is not found, the request will succeed but no - action will be taken on the server and a completed - [Operation][google.longrunning.Operation] will be returned. - - Useful for idempotent deletion. - validate_only (bool): - If set, only validate the request, but do not - actually delete the resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=2, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class GenerateAzureAccessTokenRequest(proto.Message): - r"""Request message for ``AzureClusters.GenerateAzureAccessToken`` - method. - - Attributes: - azure_cluster (str): - Required. The name of the - [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] - resource to authenticate to. - - ``AzureCluster`` names are formatted as - ``projects//locations//azureClusters/``. - - See `Resource - Names `__ - for more details on Google Cloud resource names. - """ - - azure_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateAzureAccessTokenResponse(proto.Message): - r"""Response message for ``AzureClusters.GenerateAzureAccessToken`` - method. - - Attributes: - access_token (str): - Output only. Access token to authenticate to - k8s api-server. - expiration_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp at which the token - will expire. - """ - - access_token: str = proto.Field( - proto.STRING, - number=1, - ) - expiration_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class GenerateAzureClusterAgentTokenRequest(proto.Message): - r""" - - Attributes: - azure_cluster (str): - Required. - subject_token (str): - Required. - subject_token_type (str): - Required. - version (str): - Required. - node_pool_id (str): - Optional. - grant_type (str): - Optional. - audience (str): - Optional. - scope (str): - Optional. - requested_token_type (str): - Optional. - options (str): - Optional. - """ - - azure_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - subject_token: str = proto.Field( - proto.STRING, - number=2, - ) - subject_token_type: str = proto.Field( - proto.STRING, - number=3, - ) - version: str = proto.Field( - proto.STRING, - number=4, - ) - node_pool_id: str = proto.Field( - proto.STRING, - number=5, - ) - grant_type: str = proto.Field( - proto.STRING, - number=6, - ) - audience: str = proto.Field( - proto.STRING, - number=7, - ) - scope: str = proto.Field( - proto.STRING, - number=8, - ) - requested_token_type: str = proto.Field( - proto.STRING, - number=9, - ) - options: str = proto.Field( - proto.STRING, - number=10, - ) - - -class GenerateAzureClusterAgentTokenResponse(proto.Message): - r""" - - Attributes: - access_token (str): - - expires_in (int): - - token_type (str): - - """ - - access_token: str = proto.Field( - proto.STRING, - number=1, - ) - expires_in: int = proto.Field( - proto.INT32, - number=2, - ) - token_type: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/common_resources.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/common_resources.py deleted file mode 100644 index 23539815d1f1..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/google/cloud/gke_multicloud_v1/types/common_resources.py +++ /dev/null @@ -1,576 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.gkemulticloud.v1', - manifest={ - 'Jwk', - 'WorkloadIdentityConfig', - 'MaxPodsConstraint', - 'OperationMetadata', - 'NodeTaint', - 'NodeKubeletConfig', - 'Fleet', - 'LoggingConfig', - 'LoggingComponentConfig', - 'MonitoringConfig', - 'ManagedPrometheusConfig', - 'CloudMonitoringConfig', - 'BinaryAuthorization', - 'SecurityPostureConfig', - }, -) - - -class Jwk(proto.Message): - r"""Jwk is a JSON Web Key as specified in RFC 7517. - - Attributes: - kty (str): - Key Type. - alg (str): - Algorithm. - use (str): - Permitted uses for the public keys. - kid (str): - Key ID. - n (str): - Used for RSA keys. - e (str): - Used for RSA keys. - x (str): - Used for ECDSA keys. - y (str): - Used for ECDSA keys. - crv (str): - Used for ECDSA keys. - """ - - kty: str = proto.Field( - proto.STRING, - number=1, - ) - alg: str = proto.Field( - proto.STRING, - number=2, - ) - use: str = proto.Field( - proto.STRING, - number=3, - ) - kid: str = proto.Field( - proto.STRING, - number=4, - ) - n: str = proto.Field( - proto.STRING, - number=5, - ) - e: str = proto.Field( - proto.STRING, - number=6, - ) - x: str = proto.Field( - proto.STRING, - number=7, - ) - y: str = proto.Field( - proto.STRING, - number=8, - ) - crv: str = proto.Field( - proto.STRING, - number=9, - ) - - -class WorkloadIdentityConfig(proto.Message): - r"""Workload Identity settings. - - Attributes: - issuer_uri (str): - The OIDC issuer URL for this cluster. - workload_pool (str): - The Workload Identity Pool associated to the - cluster. - identity_provider (str): - The ID of the OIDC Identity Provider (IdP) - associated to the Workload Identity Pool. - """ - - issuer_uri: str = proto.Field( - proto.STRING, - number=1, - ) - workload_pool: str = proto.Field( - proto.STRING, - number=2, - ) - identity_provider: str = proto.Field( - proto.STRING, - number=3, - ) - - -class MaxPodsConstraint(proto.Message): - r"""Constraints applied to pods. - - Attributes: - max_pods_per_node (int): - Required. The maximum number of pods to - schedule on a single node. - """ - - max_pods_per_node: int = proto.Field( - proto.INT64, - number=1, - ) - - -class OperationMetadata(proto.Message): - r"""Metadata about a long-running operation. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this operation - was created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this operation - was completed. - target (str): - Output only. The name of the resource - associated to this operation. - status_detail (str): - Output only. Human-readable status of the - operation, if any. - error_detail (str): - Output only. Human-readable status of any - error that occurred during the operation. - verb (str): - Output only. The verb associated with the API - method which triggered this operation. Possible - values are "create", "delete", "update" and - "import". - requested_cancellation (bool): - Output only. Identifies whether it has been requested - cancellation for the operation. Operations that have - successfully been cancelled have - [google.longrunning.Operation.error][google.longrunning.Operation.error] - value with a - [google.rpc.Status.code][google.rpc.Status.code] of 1, - corresponding to ``Code.CANCELLED``. - """ - - 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, - ) - status_detail: str = proto.Field( - proto.STRING, - number=4, - ) - error_detail: str = proto.Field( - proto.STRING, - number=5, - ) - verb: str = proto.Field( - proto.STRING, - number=7, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - - -class NodeTaint(proto.Message): - r"""The taint content for the node taint. - - Attributes: - key (str): - Required. Key for the taint. - value (str): - Required. Value for the taint. - effect (google.cloud.gke_multicloud_v1.types.NodeTaint.Effect): - Required. The taint effect. - """ - class Effect(proto.Enum): - r"""The taint effect. - - Values: - EFFECT_UNSPECIFIED (0): - Not set. - NO_SCHEDULE (1): - Do not allow new pods to schedule onto the - node unless they tolerate the taint, but allow - all pods submitted to Kubelet without going - through the scheduler to start, and allow all - already-running pods to continue running. - Enforced by the scheduler. - PREFER_NO_SCHEDULE (2): - Like TaintEffectNoSchedule, but the scheduler - tries not to schedule new pods onto the node, - rather than prohibiting new pods from scheduling - onto the node entirely. Enforced by the - scheduler. - NO_EXECUTE (3): - Evict any already-running pods that do not - tolerate the taint. Currently enforced by - NodeController. - """ - EFFECT_UNSPECIFIED = 0 - NO_SCHEDULE = 1 - PREFER_NO_SCHEDULE = 2 - NO_EXECUTE = 3 - - key: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - effect: Effect = proto.Field( - proto.ENUM, - number=3, - enum=Effect, - ) - - -class NodeKubeletConfig(proto.Message): - r"""Configuration for node pool kubelet options. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - insecure_kubelet_readonly_port_enabled (bool): - Optional. Enable the insecure kubelet read - only port. - cpu_manager_policy (str): - Optional. Control the CPU management policy on the node. See - https://kubernetes.io/docs/tasks/administer-cluster/cpu-management-policies/ - - The following values are allowed. - - - "none": the default, which represents the existing - scheduling behavior. - - "static": allows pods with certain resource - characteristics to be granted increased CPU affinity and - exclusivity on the node. The default value is 'none' if - unspecified. - - This field is a member of `oneof`_ ``_cpu_manager_policy``. - cpu_cfs_quota (bool): - Optional. Enable CPU CFS quota enforcement - for containers that specify CPU limits. - - This option is enabled by default which makes - kubelet use CFS quota - (https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt) - to enforce container CPU limits. Otherwise, CPU - limits will not be enforced at all. - - Disable this option to mitigate CPU throttling - problems while still having your pods to be in - Guaranteed QoS class by specifying the CPU - limits. - - The default value is 'true' if unspecified. - - This field is a member of `oneof`_ ``_cpu_cfs_quota``. - cpu_cfs_quota_period (str): - Optional. Set the CPU CFS quota period value - 'cpu.cfs_period_us'. - - The string must be a sequence of decimal numbers, each with - optional fraction and a unit suffix, such as "300ms". Valid - time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". - The value must be a positive duration. - - The default value is '100ms' if unspecified. - - This field is a member of `oneof`_ ``_cpu_cfs_quota_period``. - pod_pids_limit (int): - Optional. Set the Pod PID limits. See - https://kubernetes.io/docs/concepts/policy/pid-limiting/#pod-pid-limits - - Controls the maximum number of processes allowed - to run in a pod. The value must be greater than - or equal to 1024 and less than 4194304. - - This field is a member of `oneof`_ ``_pod_pids_limit``. - """ - - insecure_kubelet_readonly_port_enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - cpu_manager_policy: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - cpu_cfs_quota: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - cpu_cfs_quota_period: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - pod_pids_limit: int = proto.Field( - proto.INT64, - number=5, - optional=True, - ) - - -class Fleet(proto.Message): - r"""Fleet related configuration. - - Fleets are a Google Cloud concept for logically organizing clusters, - letting you use and manage multi-cluster capabilities and apply - consistent policies across your systems. - - See `Anthos - Fleets `__ - for more details on Anthos multi-cluster capabilities using Fleets. - - Attributes: - project (str): - Required. The name of the Fleet host project where this - cluster will be registered. - - Project names are formatted as - ``projects/``. - membership (str): - Output only. The name of the managed Hub Membership resource - associated to this cluster. - - Membership names are formatted as - ``projects//locations/global/membership/``. - """ - - project: str = proto.Field( - proto.STRING, - number=1, - ) - membership: str = proto.Field( - proto.STRING, - number=2, - ) - - -class LoggingConfig(proto.Message): - r"""Parameters that describe the Logging configuration in a - cluster. - - Attributes: - component_config (google.cloud.gke_multicloud_v1.types.LoggingComponentConfig): - The configuration of the logging components; - """ - - component_config: 'LoggingComponentConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='LoggingComponentConfig', - ) - - -class LoggingComponentConfig(proto.Message): - r"""Parameters that describe the Logging component configuration - in a cluster. - - Attributes: - enable_components (MutableSequence[google.cloud.gke_multicloud_v1.types.LoggingComponentConfig.Component]): - The components to be enabled. - """ - class Component(proto.Enum): - r"""The components of the logging configuration; - - Values: - COMPONENT_UNSPECIFIED (0): - No component is specified - SYSTEM_COMPONENTS (1): - This indicates that system logging components - is enabled. - WORKLOADS (2): - This indicates that user workload logging - component is enabled. - """ - COMPONENT_UNSPECIFIED = 0 - SYSTEM_COMPONENTS = 1 - WORKLOADS = 2 - - enable_components: MutableSequence[Component] = proto.RepeatedField( - proto.ENUM, - number=1, - enum=Component, - ) - - -class MonitoringConfig(proto.Message): - r"""Parameters that describe the Monitoring configuration in a - cluster. - - Attributes: - managed_prometheus_config (google.cloud.gke_multicloud_v1.types.ManagedPrometheusConfig): - Enable Google Cloud Managed Service for - Prometheus in the cluster. - cloud_monitoring_config (google.cloud.gke_multicloud_v1.types.CloudMonitoringConfig): - Optionally enable GKE metrics. - Only for Attached Clusters. - """ - - managed_prometheus_config: 'ManagedPrometheusConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='ManagedPrometheusConfig', - ) - cloud_monitoring_config: 'CloudMonitoringConfig' = proto.Field( - proto.MESSAGE, - number=4, - message='CloudMonitoringConfig', - ) - - -class ManagedPrometheusConfig(proto.Message): - r"""ManagedPrometheusConfig defines the configuration for - Google Cloud Managed Service for Prometheus. - - Attributes: - enabled (bool): - Enable Managed Collection. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - - -class CloudMonitoringConfig(proto.Message): - r"""CloudMonitoringConfig defines the configuration for - built-in Cloud Logging and Monitoring. - Only for Attached Clusters. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - enabled (bool): - Enable GKE-native logging and metrics. - Only for Attached Clusters. - - This field is a member of `oneof`_ ``_enabled``. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - - -class BinaryAuthorization(proto.Message): - r"""Configuration for Binary Authorization. - - Attributes: - evaluation_mode (google.cloud.gke_multicloud_v1.types.BinaryAuthorization.EvaluationMode): - Mode of operation for binauthz policy - evaluation. If unspecified, defaults to - DISABLED. - """ - class EvaluationMode(proto.Enum): - r"""Binary Authorization mode of operation. - - Values: - EVALUATION_MODE_UNSPECIFIED (0): - Default value - DISABLED (1): - Disable BinaryAuthorization - PROJECT_SINGLETON_POLICY_ENFORCE (2): - Enforce Kubernetes admission requests with - BinaryAuthorization using the project's - singleton policy. - """ - EVALUATION_MODE_UNSPECIFIED = 0 - DISABLED = 1 - PROJECT_SINGLETON_POLICY_ENFORCE = 2 - - evaluation_mode: EvaluationMode = proto.Field( - proto.ENUM, - number=1, - enum=EvaluationMode, - ) - - -class SecurityPostureConfig(proto.Message): - r"""SecurityPostureConfig defines the flags needed to - enable/disable features for the Security Posture API. - - Attributes: - vulnerability_mode (google.cloud.gke_multicloud_v1.types.SecurityPostureConfig.VulnerabilityMode): - Sets which mode to use for vulnerability - scanning. - """ - class VulnerabilityMode(proto.Enum): - r"""VulnerabilityMode defines enablement mode for vulnerability - scanning. - - Values: - VULNERABILITY_MODE_UNSPECIFIED (0): - Default value not specified. - VULNERABILITY_DISABLED (1): - Disables vulnerability scanning on the - cluster. - VULNERABILITY_ENTERPRISE (2): - Applies the Security Posture's vulnerability - on cluster Enterprise level features. - """ - VULNERABILITY_MODE_UNSPECIFIED = 0 - VULNERABILITY_DISABLED = 1 - VULNERABILITY_ENTERPRISE = 2 - - vulnerability_mode: VulnerabilityMode = proto.Field( - proto.ENUM, - number=1, - enum=VulnerabilityMode, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/mypy.ini b/owl-bot-staging/google-cloud-gke-multicloud/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/noxfile.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/noxfile.py deleted file mode 100644 index 5736281f802e..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-gke-multicloud' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/gke_multicloud_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/gke_multicloud_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-p', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py deleted file mode 100644 index 3e9e298ad4a1..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAttachedCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_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 gke_multicloud_v1 - - -async def sample_create_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - attached_cluster = gke_multicloud_v1.AttachedCluster() - attached_cluster.platform_version = "platform_version_value" - attached_cluster.distribution = "distribution_value" - attached_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAttachedClusterRequest( - parent="parent_value", - attached_cluster=attached_cluster, - attached_cluster_id="attached_cluster_id_value", - ) - - # Make the request - operation = client.create_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py deleted file mode 100644 index fcd93bbd900c..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAttachedCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_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 gke_multicloud_v1 - - -def sample_create_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - attached_cluster = gke_multicloud_v1.AttachedCluster() - attached_cluster.platform_version = "platform_version_value" - attached_cluster.distribution = "distribution_value" - attached_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAttachedClusterRequest( - parent="parent_value", - attached_cluster=attached_cluster, - attached_cluster_id="attached_cluster_id_value", - ) - - # Make the request - operation = client.create_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py deleted file mode 100644 index 26add76e189c..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAttachedCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_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 gke_multicloud_v1 - - -async def sample_delete_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAttachedClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py deleted file mode 100644 index ed906b0ac7fe..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAttachedCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_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 gke_multicloud_v1 - - -def sample_delete_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAttachedClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py deleted file mode 100644 index 14e7c5e9afb4..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAttachedClusterAgentToken -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_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 gke_multicloud_v1 - - -async def sample_generate_attached_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAttachedClusterAgentTokenRequest( - attached_cluster="attached_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = await client.generate_attached_cluster_agent_token(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py deleted file mode 100644 index 40d3bf89d09d..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAttachedClusterAgentToken -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_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 gke_multicloud_v1 - - -def sample_generate_attached_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAttachedClusterAgentTokenRequest( - attached_cluster="attached_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = client.generate_attached_cluster_agent_token(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py deleted file mode 100644 index 544e71cdbc9c..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAttachedClusterInstallManifest -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_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 gke_multicloud_v1 - - -async def sample_generate_attached_cluster_install_manifest(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAttachedClusterInstallManifestRequest( - parent="parent_value", - attached_cluster_id="attached_cluster_id_value", - platform_version="platform_version_value", - ) - - # Make the request - response = await client.generate_attached_cluster_install_manifest(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py deleted file mode 100644 index ed3a9fe0075e..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAttachedClusterInstallManifest -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_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 gke_multicloud_v1 - - -def sample_generate_attached_cluster_install_manifest(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAttachedClusterInstallManifestRequest( - parent="parent_value", - attached_cluster_id="attached_cluster_id_value", - platform_version="platform_version_value", - ) - - # Make the request - response = client.generate_attached_cluster_install_manifest(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py deleted file mode 100644 index b5d7da17a336..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttachedCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_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 gke_multicloud_v1 - - -async def sample_get_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAttachedClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attached_cluster(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py deleted file mode 100644 index 1b21ca1906a3..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttachedCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_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 gke_multicloud_v1 - - -def sample_get_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAttachedClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_attached_cluster(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py deleted file mode 100644 index 827c4d5c6540..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttachedServerConfig -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_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 gke_multicloud_v1 - - -async def sample_get_attached_server_config(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAttachedServerConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_attached_server_config(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py deleted file mode 100644 index 76490ea3abd0..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAttachedServerConfig -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_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 gke_multicloud_v1 - - -def sample_get_attached_server_config(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAttachedServerConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_attached_server_config(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py deleted file mode 100644 index 9b94d8986875..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportAttachedCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_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 gke_multicloud_v1 - - -async def sample_import_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ImportAttachedClusterRequest( - parent="parent_value", - fleet_membership="fleet_membership_value", - platform_version="platform_version_value", - distribution="distribution_value", - ) - - # Make the request - operation = client.import_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py deleted file mode 100644 index 59c919ab77a2..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportAttachedCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_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 gke_multicloud_v1 - - -def sample_import_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ImportAttachedClusterRequest( - parent="parent_value", - fleet_membership="fleet_membership_value", - platform_version="platform_version_value", - distribution="distribution_value", - ) - - # Make the request - operation = client.import_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py deleted file mode 100644 index bc0bb3e08bf1..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAttachedClusters -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_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 gke_multicloud_v1 - - -async def sample_list_attached_clusters(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAttachedClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attached_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py deleted file mode 100644 index c30c113a6b3f..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAttachedClusters -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_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 gke_multicloud_v1 - - -def sample_list_attached_clusters(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAttachedClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attached_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py deleted file mode 100644 index ebbf06cbdb91..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttachedCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_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 gke_multicloud_v1 - - -async def sample_update_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersAsyncClient() - - # Initialize request argument(s) - attached_cluster = gke_multicloud_v1.AttachedCluster() - attached_cluster.platform_version = "platform_version_value" - attached_cluster.distribution = "distribution_value" - attached_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAttachedClusterRequest( - attached_cluster=attached_cluster, - ) - - # Make the request - operation = client.update_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py deleted file mode 100644 index e2854cc7dd0c..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAttachedCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_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 gke_multicloud_v1 - - -def sample_update_attached_cluster(): - # Create a client - client = gke_multicloud_v1.AttachedClustersClient() - - # Initialize request argument(s) - attached_cluster = gke_multicloud_v1.AttachedCluster() - attached_cluster.platform_version = "platform_version_value" - attached_cluster.distribution = "distribution_value" - attached_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAttachedClusterRequest( - attached_cluster=attached_cluster, - ) - - # Make the request - operation = client.update_attached_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py deleted file mode 100644 index be6bd6e71991..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAwsCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_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 gke_multicloud_v1 - - -async def sample_create_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - aws_cluster = gke_multicloud_v1.AwsCluster() - aws_cluster.networking.vpc_id = "vpc_id_value" - aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - aws_cluster.aws_region = "aws_region_value" - aws_cluster.control_plane.version = "version_value" - aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] - aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" - aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" - aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAwsClusterRequest( - parent="parent_value", - aws_cluster=aws_cluster, - aws_cluster_id="aws_cluster_id_value", - ) - - # Make the request - operation = client.create_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py deleted file mode 100644 index 7b67dfa0e9da..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAwsCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_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 gke_multicloud_v1 - - -def sample_create_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - aws_cluster = gke_multicloud_v1.AwsCluster() - aws_cluster.networking.vpc_id = "vpc_id_value" - aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - aws_cluster.aws_region = "aws_region_value" - aws_cluster.control_plane.version = "version_value" - aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] - aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" - aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" - aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAwsClusterRequest( - parent="parent_value", - aws_cluster=aws_cluster, - aws_cluster_id="aws_cluster_id_value", - ) - - # Make the request - operation = client.create_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py deleted file mode 100644 index e00d6b4fcd4f..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAwsNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_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 gke_multicloud_v1 - - -async def sample_create_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - aws_node_pool = gke_multicloud_v1.AwsNodePool() - aws_node_pool.version = "version_value" - aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" - aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_node_pool.autoscaling.min_node_count = 1489 - aws_node_pool.autoscaling.max_node_count = 1491 - aws_node_pool.subnet_id = "subnet_id_value" - aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.CreateAwsNodePoolRequest( - parent="parent_value", - aws_node_pool=aws_node_pool, - aws_node_pool_id="aws_node_pool_id_value", - ) - - # Make the request - operation = client.create_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py deleted file mode 100644 index 649220317513..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAwsNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_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 gke_multicloud_v1 - - -def sample_create_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - aws_node_pool = gke_multicloud_v1.AwsNodePool() - aws_node_pool.version = "version_value" - aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" - aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_node_pool.autoscaling.min_node_count = 1489 - aws_node_pool.autoscaling.max_node_count = 1491 - aws_node_pool.subnet_id = "subnet_id_value" - aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.CreateAwsNodePoolRequest( - parent="parent_value", - aws_node_pool=aws_node_pool, - aws_node_pool_id="aws_node_pool_id_value", - ) - - # Make the request - operation = client.create_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py deleted file mode 100644 index 11f7b3d31c82..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAwsCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_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 gke_multicloud_v1 - - -async def sample_delete_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAwsClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py deleted file mode 100644 index da1f735bf176..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAwsCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_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 gke_multicloud_v1 - - -def sample_delete_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAwsClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py deleted file mode 100644 index e5307f87c3fa..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAwsNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_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 gke_multicloud_v1 - - -async def sample_delete_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAwsNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py deleted file mode 100644 index 92f7d4c6f658..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAwsNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_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 gke_multicloud_v1 - - -def sample_delete_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAwsNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py deleted file mode 100644 index 0c83d56f3c0d..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAwsAccessToken -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_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 gke_multicloud_v1 - - -async def sample_generate_aws_access_token(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAwsAccessTokenRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = await client.generate_aws_access_token(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py deleted file mode 100644 index be14e3b8d261..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAwsAccessToken -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_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 gke_multicloud_v1 - - -def sample_generate_aws_access_token(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAwsAccessTokenRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = client.generate_aws_access_token(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py deleted file mode 100644 index a3b9a7e4e299..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAwsClusterAgentToken -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_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 gke_multicloud_v1 - - -async def sample_generate_aws_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAwsClusterAgentTokenRequest( - aws_cluster="aws_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = await client.generate_aws_cluster_agent_token(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py deleted file mode 100644 index 01d8c89476eb..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAwsClusterAgentToken -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_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 gke_multicloud_v1 - - -def sample_generate_aws_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAwsClusterAgentTokenRequest( - aws_cluster="aws_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = client.generate_aws_cluster_agent_token(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py deleted file mode 100644 index d9470ec7f6bc..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAwsCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_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 gke_multicloud_v1 - - -async def sample_get_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_aws_cluster(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py deleted file mode 100644 index 85769c701dab..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAwsCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_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 gke_multicloud_v1 - - -def sample_get_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_aws_cluster(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py deleted file mode 100644 index 6f731bd2767c..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAwsJsonWebKeys -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_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 gke_multicloud_v1 - - -async def sample_get_aws_json_web_keys(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsJsonWebKeysRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = await client.get_aws_json_web_keys(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py deleted file mode 100644 index 61a988ed4d0f..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAwsJsonWebKeys -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_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 gke_multicloud_v1 - - -def sample_get_aws_json_web_keys(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsJsonWebKeysRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = client.get_aws_json_web_keys(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py deleted file mode 100644 index 0e239d2d4dfa..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAwsNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_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 gke_multicloud_v1 - - -async def sample_get_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsNodePoolRequest( - name="name_value", - ) - - # Make the request - response = await client.get_aws_node_pool(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py deleted file mode 100644 index b38d3a435f8d..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAwsNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_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 gke_multicloud_v1 - - -def sample_get_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsNodePoolRequest( - name="name_value", - ) - - # Make the request - response = client.get_aws_node_pool(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py deleted file mode 100644 index 4f7f579d6fe4..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAwsOpenIdConfig -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_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 gke_multicloud_v1 - - -async def sample_get_aws_open_id_config(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsOpenIdConfigRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = await client.get_aws_open_id_config(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py deleted file mode 100644 index 5e9f5832cb61..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAwsOpenIdConfig -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_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 gke_multicloud_v1 - - -def sample_get_aws_open_id_config(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsOpenIdConfigRequest( - aws_cluster="aws_cluster_value", - ) - - # Make the request - response = client.get_aws_open_id_config(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py deleted file mode 100644 index 575495d24b13..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAwsServerConfig -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_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 gke_multicloud_v1 - - -async def sample_get_aws_server_config(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsServerConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_aws_server_config(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py deleted file mode 100644 index 3c5599d28c0d..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAwsServerConfig -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_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 gke_multicloud_v1 - - -def sample_get_aws_server_config(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAwsServerConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_aws_server_config(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py deleted file mode 100644 index 31168fe1b810..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAwsClusters -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_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 gke_multicloud_v1 - - -async def sample_list_aws_clusters(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAwsClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_aws_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py deleted file mode 100644 index a68f90e25840..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAwsClusters -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_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 gke_multicloud_v1 - - -def sample_list_aws_clusters(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAwsClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_aws_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py deleted file mode 100644 index 4749bf7f5753..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAwsNodePools -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_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 gke_multicloud_v1 - - -async def sample_list_aws_node_pools(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAwsNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_aws_node_pools(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py deleted file mode 100644 index ffb0a4efc524..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAwsNodePools -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_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 gke_multicloud_v1 - - -def sample_list_aws_node_pools(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAwsNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_aws_node_pools(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py deleted file mode 100644 index 1831c8ccfe7a..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RollbackAwsNodePoolUpdate -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_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 gke_multicloud_v1 - - -async def sample_rollback_aws_node_pool_update(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.RollbackAwsNodePoolUpdateRequest( - name="name_value", - ) - - # Make the request - operation = client.rollback_aws_node_pool_update(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py deleted file mode 100644 index e9c031e87a74..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RollbackAwsNodePoolUpdate -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_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 gke_multicloud_v1 - - -def sample_rollback_aws_node_pool_update(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.RollbackAwsNodePoolUpdateRequest( - name="name_value", - ) - - # Make the request - operation = client.rollback_aws_node_pool_update(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py deleted file mode 100644 index 599830b6a8db..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAwsCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_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 gke_multicloud_v1 - - -async def sample_update_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - aws_cluster = gke_multicloud_v1.AwsCluster() - aws_cluster.networking.vpc_id = "vpc_id_value" - aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - aws_cluster.aws_region = "aws_region_value" - aws_cluster.control_plane.version = "version_value" - aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] - aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" - aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" - aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAwsClusterRequest( - aws_cluster=aws_cluster, - ) - - # Make the request - operation = client.update_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py deleted file mode 100644 index 0d47bec19742..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAwsCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_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 gke_multicloud_v1 - - -def sample_update_aws_cluster(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - aws_cluster = gke_multicloud_v1.AwsCluster() - aws_cluster.networking.vpc_id = "vpc_id_value" - aws_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - aws_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - aws_cluster.aws_region = "aws_region_value" - aws_cluster.control_plane.version = "version_value" - aws_cluster.control_plane.subnet_ids = ['subnet_ids_value1', 'subnet_ids_value2'] - aws_cluster.control_plane.iam_instance_profile = "iam_instance_profile_value" - aws_cluster.control_plane.database_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.control_plane.aws_services_authentication.role_arn = "role_arn_value" - aws_cluster.control_plane.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAwsClusterRequest( - aws_cluster=aws_cluster, - ) - - # Make the request - operation = client.update_aws_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py deleted file mode 100644 index 5c336772653c..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAwsNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_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 gke_multicloud_v1 - - -async def sample_update_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersAsyncClient() - - # Initialize request argument(s) - aws_node_pool = gke_multicloud_v1.AwsNodePool() - aws_node_pool.version = "version_value" - aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" - aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_node_pool.autoscaling.min_node_count = 1489 - aws_node_pool.autoscaling.max_node_count = 1491 - aws_node_pool.subnet_id = "subnet_id_value" - aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.UpdateAwsNodePoolRequest( - aws_node_pool=aws_node_pool, - ) - - # Make the request - operation = client.update_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py deleted file mode 100644 index 2e4fb0a3cc29..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAwsNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_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 gke_multicloud_v1 - - -def sample_update_aws_node_pool(): - # Create a client - client = gke_multicloud_v1.AwsClustersClient() - - # Initialize request argument(s) - aws_node_pool = gke_multicloud_v1.AwsNodePool() - aws_node_pool.version = "version_value" - aws_node_pool.config.iam_instance_profile = "iam_instance_profile_value" - aws_node_pool.config.config_encryption.kms_key_arn = "kms_key_arn_value" - aws_node_pool.autoscaling.min_node_count = 1489 - aws_node_pool.autoscaling.max_node_count = 1491 - aws_node_pool.subnet_id = "subnet_id_value" - aws_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.UpdateAwsNodePoolRequest( - aws_node_pool=aws_node_pool, - ) - - # Make the request - operation = client.update_aws_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py deleted file mode 100644 index d08247c0e32f..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAzureClient -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_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 gke_multicloud_v1 - - -async def sample_create_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - azure_client = gke_multicloud_v1.AzureClient() - azure_client.tenant_id = "tenant_id_value" - azure_client.application_id = "application_id_value" - - request = gke_multicloud_v1.CreateAzureClientRequest( - parent="parent_value", - azure_client=azure_client, - azure_client_id="azure_client_id_value", - ) - - # Make the request - operation = client.create_azure_client(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py deleted file mode 100644 index 3de1be17e9e0..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAzureClient -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_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 gke_multicloud_v1 - - -def sample_create_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - azure_client = gke_multicloud_v1.AzureClient() - azure_client.tenant_id = "tenant_id_value" - azure_client.application_id = "application_id_value" - - request = gke_multicloud_v1.CreateAzureClientRequest( - parent="parent_value", - azure_client=azure_client, - azure_client_id="azure_client_id_value", - ) - - # Make the request - operation = client.create_azure_client(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py deleted file mode 100644 index 8a83f88ae20b..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAzureCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_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 gke_multicloud_v1 - - -async def sample_create_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - azure_cluster = gke_multicloud_v1.AzureCluster() - azure_cluster.azure_region = "azure_region_value" - azure_cluster.resource_group_id = "resource_group_id_value" - azure_cluster.networking.virtual_network_id = "virtual_network_id_value" - azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - azure_cluster.control_plane.version = "version_value" - azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" - azure_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAzureClusterRequest( - parent="parent_value", - azure_cluster=azure_cluster, - azure_cluster_id="azure_cluster_id_value", - ) - - # Make the request - operation = client.create_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py deleted file mode 100644 index 35f26bf00e4c..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAzureCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_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 gke_multicloud_v1 - - -def sample_create_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - azure_cluster = gke_multicloud_v1.AzureCluster() - azure_cluster.azure_region = "azure_region_value" - azure_cluster.resource_group_id = "resource_group_id_value" - azure_cluster.networking.virtual_network_id = "virtual_network_id_value" - azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - azure_cluster.control_plane.version = "version_value" - azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" - azure_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.CreateAzureClusterRequest( - parent="parent_value", - azure_cluster=azure_cluster, - azure_cluster_id="azure_cluster_id_value", - ) - - # Make the request - operation = client.create_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py deleted file mode 100644 index 09cc4343d068..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAzureNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_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 gke_multicloud_v1 - - -async def sample_create_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - azure_node_pool = gke_multicloud_v1.AzureNodePool() - azure_node_pool.version = "version_value" - azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" - azure_node_pool.subnet_id = "subnet_id_value" - azure_node_pool.autoscaling.min_node_count = 1489 - azure_node_pool.autoscaling.max_node_count = 1491 - azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.CreateAzureNodePoolRequest( - parent="parent_value", - azure_node_pool=azure_node_pool, - azure_node_pool_id="azure_node_pool_id_value", - ) - - # Make the request - operation = client.create_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py deleted file mode 100644 index f88947000da6..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAzureNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_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 gke_multicloud_v1 - - -def sample_create_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - azure_node_pool = gke_multicloud_v1.AzureNodePool() - azure_node_pool.version = "version_value" - azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" - azure_node_pool.subnet_id = "subnet_id_value" - azure_node_pool.autoscaling.min_node_count = 1489 - azure_node_pool.autoscaling.max_node_count = 1491 - azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.CreateAzureNodePoolRequest( - parent="parent_value", - azure_node_pool=azure_node_pool, - azure_node_pool_id="azure_node_pool_id_value", - ) - - # Make the request - operation = client.create_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py deleted file mode 100644 index 4e1c0ee35861..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAzureClient -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_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 gke_multicloud_v1 - - -async def sample_delete_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureClientRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_client(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py deleted file mode 100644 index ec3297977d12..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAzureClient -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_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 gke_multicloud_v1 - - -def sample_delete_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureClientRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_client(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py deleted file mode 100644 index 96c20cdd55f1..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAzureCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_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 gke_multicloud_v1 - - -async def sample_delete_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py deleted file mode 100644 index 0dd1750c9fe9..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAzureCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_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 gke_multicloud_v1 - - -def sample_delete_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py deleted file mode 100644 index af626d99ca9f..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAzureNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_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 gke_multicloud_v1 - - -async def sample_delete_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py deleted file mode 100644 index 2e3b80e11752..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAzureNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_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 gke_multicloud_v1 - - -def sample_delete_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.DeleteAzureNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py deleted file mode 100644 index c7f45cbacde2..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAzureAccessToken -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_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 gke_multicloud_v1 - - -async def sample_generate_azure_access_token(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAzureAccessTokenRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = await client.generate_azure_access_token(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py deleted file mode 100644 index 4ca5ec07e9a6..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAzureAccessToken -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_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 gke_multicloud_v1 - - -def sample_generate_azure_access_token(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAzureAccessTokenRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = client.generate_azure_access_token(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py deleted file mode 100644 index 77828cc130b0..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAzureClusterAgentToken -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_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 gke_multicloud_v1 - - -async def sample_generate_azure_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAzureClusterAgentTokenRequest( - azure_cluster="azure_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = await client.generate_azure_cluster_agent_token(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py deleted file mode 100644 index 42e1f3278668..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAzureClusterAgentToken -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_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 gke_multicloud_v1 - - -def sample_generate_azure_cluster_agent_token(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GenerateAzureClusterAgentTokenRequest( - azure_cluster="azure_cluster_value", - subject_token="subject_token_value", - subject_token_type="subject_token_type_value", - version="version_value", - ) - - # Make the request - response = client.generate_azure_cluster_agent_token(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py deleted file mode 100644 index 6443b3d16d37..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureClient -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureClient_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 gke_multicloud_v1 - - -async def sample_get_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureClientRequest( - name="name_value", - ) - - # Make the request - response = await client.get_azure_client(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureClient_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py deleted file mode 100644 index 070a7f4ac0df..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureClient -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureClient_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 gke_multicloud_v1 - - -def sample_get_azure_client(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureClientRequest( - name="name_value", - ) - - # Make the request - response = client.get_azure_client(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureClient_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py deleted file mode 100644 index bab6585f3ce3..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_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 gke_multicloud_v1 - - -async def sample_get_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_azure_cluster(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py deleted file mode 100644 index 20cfcf7ba59a..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_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 gke_multicloud_v1 - - -def sample_get_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_azure_cluster(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py deleted file mode 100644 index 5e288213c015..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureJsonWebKeys -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_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 gke_multicloud_v1 - - -async def sample_get_azure_json_web_keys(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureJsonWebKeysRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = await client.get_azure_json_web_keys(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py deleted file mode 100644 index 75e51160764d..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureJsonWebKeys -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_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 gke_multicloud_v1 - - -def sample_get_azure_json_web_keys(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureJsonWebKeysRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = client.get_azure_json_web_keys(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py deleted file mode 100644 index f1bdfe5372ee..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_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 gke_multicloud_v1 - - -async def sample_get_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureNodePoolRequest( - name="name_value", - ) - - # Make the request - response = await client.get_azure_node_pool(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py deleted file mode 100644 index 1a6852417a82..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_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 gke_multicloud_v1 - - -def sample_get_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureNodePoolRequest( - name="name_value", - ) - - # Make the request - response = client.get_azure_node_pool(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py deleted file mode 100644 index 27154b26d7cd..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureOpenIdConfig -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_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 gke_multicloud_v1 - - -async def sample_get_azure_open_id_config(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureOpenIdConfigRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = await client.get_azure_open_id_config(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py deleted file mode 100644 index a1a893e498b8..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureOpenIdConfig -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_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 gke_multicloud_v1 - - -def sample_get_azure_open_id_config(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureOpenIdConfigRequest( - azure_cluster="azure_cluster_value", - ) - - # Make the request - response = client.get_azure_open_id_config(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py deleted file mode 100644 index a8977ab891c4..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureServerConfig -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_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 gke_multicloud_v1 - - -async def sample_get_azure_server_config(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureServerConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_azure_server_config(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py deleted file mode 100644 index bec52cb720fe..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAzureServerConfig -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_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 gke_multicloud_v1 - - -def sample_get_azure_server_config(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.GetAzureServerConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_azure_server_config(request=request) - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py deleted file mode 100644 index c34a6bdd6b86..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAzureClients -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_ListAzureClients_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 gke_multicloud_v1 - - -async def sample_list_azure_clients(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureClientsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_clients(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_ListAzureClients_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py deleted file mode 100644 index 2428b5587882..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAzureClients -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_ListAzureClients_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 gke_multicloud_v1 - - -def sample_list_azure_clients(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureClientsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_clients(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_ListAzureClients_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py deleted file mode 100644 index a9eb485ba74a..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAzureClusters -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_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 gke_multicloud_v1 - - -async def sample_list_azure_clusters(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py deleted file mode 100644 index 19ddcdc67662..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAzureClusters -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_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 gke_multicloud_v1 - - -def sample_list_azure_clusters(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py deleted file mode 100644 index 2f119291ad50..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAzureNodePools -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_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 gke_multicloud_v1 - - -async def sample_list_azure_node_pools(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_node_pools(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py deleted file mode 100644 index 48887c75dec4..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAzureNodePools -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_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 gke_multicloud_v1 - - -def sample_list_azure_node_pools(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - request = gke_multicloud_v1.ListAzureNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_azure_node_pools(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py deleted file mode 100644 index 66b255ccfc27..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAzureCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_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 gke_multicloud_v1 - - -async def sample_update_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - azure_cluster = gke_multicloud_v1.AzureCluster() - azure_cluster.azure_region = "azure_region_value" - azure_cluster.resource_group_id = "resource_group_id_value" - azure_cluster.networking.virtual_network_id = "virtual_network_id_value" - azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - azure_cluster.control_plane.version = "version_value" - azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" - azure_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAzureClusterRequest( - azure_cluster=azure_cluster, - ) - - # Make the request - operation = client.update_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py deleted file mode 100644 index 96ee39a51052..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAzureCluster -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_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 gke_multicloud_v1 - - -def sample_update_azure_cluster(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - azure_cluster = gke_multicloud_v1.AzureCluster() - azure_cluster.azure_region = "azure_region_value" - azure_cluster.resource_group_id = "resource_group_id_value" - azure_cluster.networking.virtual_network_id = "virtual_network_id_value" - azure_cluster.networking.pod_address_cidr_blocks = ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'] - azure_cluster.networking.service_address_cidr_blocks = ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'] - azure_cluster.control_plane.version = "version_value" - azure_cluster.control_plane.ssh_config.authorized_key = "authorized_key_value" - azure_cluster.fleet.project = "project_value" - - request = gke_multicloud_v1.UpdateAzureClusterRequest( - azure_cluster=azure_cluster, - ) - - # Make the request - operation = client.update_azure_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py deleted file mode 100644 index b5973a6d4fc3..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAzureNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_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 gke_multicloud_v1 - - -async def sample_update_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersAsyncClient() - - # Initialize request argument(s) - azure_node_pool = gke_multicloud_v1.AzureNodePool() - azure_node_pool.version = "version_value" - azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" - azure_node_pool.subnet_id = "subnet_id_value" - azure_node_pool.autoscaling.min_node_count = 1489 - azure_node_pool.autoscaling.max_node_count = 1491 - azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.UpdateAzureNodePoolRequest( - azure_node_pool=azure_node_pool, - ) - - # Make the request - operation = client.update_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_async] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py deleted file mode 100644 index d3e42f5ebc82..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAzureNodePool -# 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-multicloud - - -# [START gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_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 gke_multicloud_v1 - - -def sample_update_azure_node_pool(): - # Create a client - client = gke_multicloud_v1.AzureClustersClient() - - # Initialize request argument(s) - azure_node_pool = gke_multicloud_v1.AzureNodePool() - azure_node_pool.version = "version_value" - azure_node_pool.config.ssh_config.authorized_key = "authorized_key_value" - azure_node_pool.subnet_id = "subnet_id_value" - azure_node_pool.autoscaling.min_node_count = 1489 - azure_node_pool.autoscaling.max_node_count = 1491 - azure_node_pool.max_pods_constraint.max_pods_per_node = 1798 - - request = gke_multicloud_v1.UpdateAzureNodePoolRequest( - azure_node_pool=azure_node_pool, - ) - - # Make the request - operation = client.update_azure_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_sync] diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json b/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json deleted file mode 100644 index 34b757edefd0..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json +++ /dev/null @@ -1,7195 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.gkemulticloud.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-gke-multicloud", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", - "shortName": "AttachedClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.create_attached_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.CreateAttachedCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "CreateAttachedCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAttachedClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "attached_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AttachedCluster" - }, - { - "name": "attached_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_attached_cluster" - }, - "description": "Sample for CreateAttachedCluster", - "file": "gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", - "shortName": "AttachedClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.create_attached_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.CreateAttachedCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "CreateAttachedCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAttachedClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "attached_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AttachedCluster" - }, - { - "name": "attached_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_attached_cluster" - }, - "description": "Sample for CreateAttachedCluster", - "file": "gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_CreateAttachedCluster_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_attached_clusters_create_attached_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", - "shortName": "AttachedClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.delete_attached_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.DeleteAttachedCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "DeleteAttachedCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAttachedClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_attached_cluster" - }, - "description": "Sample for DeleteAttachedCluster", - "file": "gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_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": "gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", - "shortName": "AttachedClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.delete_attached_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.DeleteAttachedCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "DeleteAttachedCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAttachedClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_attached_cluster" - }, - "description": "Sample for DeleteAttachedCluster", - "file": "gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_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": "gkemulticloud_v1_generated_attached_clusters_delete_attached_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", - "shortName": "AttachedClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.generate_attached_cluster_agent_token", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GenerateAttachedClusterAgentToken", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "GenerateAttachedClusterAgentToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenResponse", - "shortName": "generate_attached_cluster_agent_token" - }, - "description": "Sample for GenerateAttachedClusterAgentToken", - "file": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", - "shortName": "AttachedClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.generate_attached_cluster_agent_token", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GenerateAttachedClusterAgentToken", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "GenerateAttachedClusterAgentToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterAgentTokenResponse", - "shortName": "generate_attached_cluster_agent_token" - }, - "description": "Sample for GenerateAttachedClusterAgentToken", - "file": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterAgentToken_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_agent_token_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", - "shortName": "AttachedClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.generate_attached_cluster_install_manifest", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GenerateAttachedClusterInstallManifest", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "GenerateAttachedClusterInstallManifest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "attached_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestResponse", - "shortName": "generate_attached_cluster_install_manifest" - }, - "description": "Sample for GenerateAttachedClusterInstallManifest", - "file": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", - "shortName": "AttachedClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.generate_attached_cluster_install_manifest", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GenerateAttachedClusterInstallManifest", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "GenerateAttachedClusterInstallManifest" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "attached_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAttachedClusterInstallManifestResponse", - "shortName": "generate_attached_cluster_install_manifest" - }, - "description": "Sample for GenerateAttachedClusterInstallManifest", - "file": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_attached_clusters_generate_attached_cluster_install_manifest_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", - "shortName": "AttachedClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.get_attached_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "GetAttachedCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAttachedClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AttachedCluster", - "shortName": "get_attached_cluster" - }, - "description": "Sample for GetAttachedCluster", - "file": "gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_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": "gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", - "shortName": "AttachedClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.get_attached_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "GetAttachedCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAttachedClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AttachedCluster", - "shortName": "get_attached_cluster" - }, - "description": "Sample for GetAttachedCluster", - "file": "gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_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": "gkemulticloud_v1_generated_attached_clusters_get_attached_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", - "shortName": "AttachedClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.get_attached_server_config", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedServerConfig", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "GetAttachedServerConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAttachedServerConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AttachedServerConfig", - "shortName": "get_attached_server_config" - }, - "description": "Sample for GetAttachedServerConfig", - "file": "gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_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": "gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", - "shortName": "AttachedClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.get_attached_server_config", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.GetAttachedServerConfig", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "GetAttachedServerConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAttachedServerConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AttachedServerConfig", - "shortName": "get_attached_server_config" - }, - "description": "Sample for GetAttachedServerConfig", - "file": "gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_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": "gkemulticloud_v1_generated_attached_clusters_get_attached_server_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", - "shortName": "AttachedClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.import_attached_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.ImportAttachedCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "ImportAttachedCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ImportAttachedClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "fleet_membership", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_attached_cluster" - }, - "description": "Sample for ImportAttachedCluster", - "file": "gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", - "shortName": "AttachedClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.import_attached_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.ImportAttachedCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "ImportAttachedCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ImportAttachedClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "fleet_membership", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_attached_cluster" - }, - "description": "Sample for ImportAttachedCluster", - "file": "gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_ImportAttachedCluster_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_attached_clusters_import_attached_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", - "shortName": "AttachedClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.list_attached_clusters", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.ListAttachedClusters", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "ListAttachedClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.attached_clusters.pagers.ListAttachedClustersAsyncPager", - "shortName": "list_attached_clusters" - }, - "description": "Sample for ListAttachedClusters", - "file": "gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_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": "gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", - "shortName": "AttachedClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.list_attached_clusters", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.ListAttachedClusters", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "ListAttachedClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAttachedClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.attached_clusters.pagers.ListAttachedClustersPager", - "shortName": "list_attached_clusters" - }, - "description": "Sample for ListAttachedClusters", - "file": "gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_ListAttachedClusters_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": "gkemulticloud_v1_generated_attached_clusters_list_attached_clusters_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient", - "shortName": "AttachedClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersAsyncClient.update_attached_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.UpdateAttachedCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "UpdateAttachedCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.UpdateAttachedClusterRequest" - }, - { - "name": "attached_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AttachedCluster" - }, - { - "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, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_attached_cluster" - }, - "description": "Sample for UpdateAttachedCluster", - "file": "gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient", - "shortName": "AttachedClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AttachedClustersClient.update_attached_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters.UpdateAttachedCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AttachedClusters", - "shortName": "AttachedClusters" - }, - "shortName": "UpdateAttachedCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.UpdateAttachedClusterRequest" - }, - { - "name": "attached_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AttachedCluster" - }, - { - "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, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_attached_cluster" - }, - "description": "Sample for UpdateAttachedCluster", - "file": "gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AttachedClusters_UpdateAttachedCluster_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_attached_clusters_update_attached_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.create_aws_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.CreateAwsCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "CreateAwsCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAwsClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "aws_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AwsCluster" - }, - { - "name": "aws_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_aws_cluster" - }, - "description": "Sample for CreateAwsCluster", - "file": "gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_async", - "segments": [ - { - "end": 70, - "start": 27, - "type": "FULL" - }, - { - "end": 70, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 60, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 67, - "start": 61, - "type": "REQUEST_EXECUTION" - }, - { - "end": 71, - "start": 68, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.create_aws_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.CreateAwsCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "CreateAwsCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAwsClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "aws_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AwsCluster" - }, - { - "name": "aws_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_aws_cluster" - }, - "description": "Sample for CreateAwsCluster", - "file": "gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_CreateAwsCluster_sync", - "segments": [ - { - "end": 70, - "start": 27, - "type": "FULL" - }, - { - "end": 70, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 60, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 67, - "start": 61, - "type": "REQUEST_EXECUTION" - }, - { - "end": 71, - "start": 68, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_aws_clusters_create_aws_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.create_aws_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.CreateAwsNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "CreateAwsNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAwsNodePoolRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "aws_node_pool", - "type": "google.cloud.gke_multicloud_v1.types.AwsNodePool" - }, - { - "name": "aws_node_pool_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_aws_node_pool" - }, - "description": "Sample for CreateAwsNodePool", - "file": "gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_async", - "segments": [ - { - "end": 66, - "start": 27, - "type": "FULL" - }, - { - "end": 66, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 63, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 67, - "start": 64, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.create_aws_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.CreateAwsNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "CreateAwsNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAwsNodePoolRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "aws_node_pool", - "type": "google.cloud.gke_multicloud_v1.types.AwsNodePool" - }, - { - "name": "aws_node_pool_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_aws_node_pool" - }, - "description": "Sample for CreateAwsNodePool", - "file": "gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_sync", - "segments": [ - { - "end": 66, - "start": 27, - "type": "FULL" - }, - { - "end": 66, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 63, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 67, - "start": 64, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_aws_clusters_create_aws_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.delete_aws_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.DeleteAwsCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "DeleteAwsCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAwsClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_aws_cluster" - }, - "description": "Sample for DeleteAwsCluster", - "file": "gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_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": "gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.delete_aws_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.DeleteAwsCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "DeleteAwsCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAwsClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_aws_cluster" - }, - "description": "Sample for DeleteAwsCluster", - "file": "gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_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": "gkemulticloud_v1_generated_aws_clusters_delete_aws_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.delete_aws_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.DeleteAwsNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "DeleteAwsNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAwsNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_aws_node_pool" - }, - "description": "Sample for DeleteAwsNodePool", - "file": "gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_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": "gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.delete_aws_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.DeleteAwsNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "DeleteAwsNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAwsNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_aws_node_pool" - }, - "description": "Sample for DeleteAwsNodePool", - "file": "gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_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": "gkemulticloud_v1_generated_aws_clusters_delete_aws_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.generate_aws_access_token", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GenerateAwsAccessToken", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GenerateAwsAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenResponse", - "shortName": "generate_aws_access_token" - }, - "description": "Sample for GenerateAwsAccessToken", - "file": "gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_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": "gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.generate_aws_access_token", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GenerateAwsAccessToken", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GenerateAwsAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAwsAccessTokenResponse", - "shortName": "generate_aws_access_token" - }, - "description": "Sample for GenerateAwsAccessToken", - "file": "gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_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": "gkemulticloud_v1_generated_aws_clusters_generate_aws_access_token_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.generate_aws_cluster_agent_token", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GenerateAwsClusterAgentToken", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GenerateAwsClusterAgentToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenResponse", - "shortName": "generate_aws_cluster_agent_token" - }, - "description": "Sample for GenerateAwsClusterAgentToken", - "file": "gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.generate_aws_cluster_agent_token", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GenerateAwsClusterAgentToken", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GenerateAwsClusterAgentToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAwsClusterAgentTokenResponse", - "shortName": "generate_aws_cluster_agent_token" - }, - "description": "Sample for GenerateAwsClusterAgentToken", - "file": "gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GenerateAwsClusterAgentToken_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_aws_clusters_generate_aws_cluster_agent_token_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.get_aws_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GetAwsCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAwsClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AwsCluster", - "shortName": "get_aws_cluster" - }, - "description": "Sample for GetAwsCluster", - "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.get_aws_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GetAwsCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAwsClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AwsCluster", - "shortName": "get_aws_cluster" - }, - "description": "Sample for GetAwsCluster", - "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.get_aws_json_web_keys", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsJsonWebKeys", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GetAwsJsonWebKeys" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAwsJsonWebKeysRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AwsJsonWebKeys", - "shortName": "get_aws_json_web_keys" - }, - "description": "Sample for GetAwsJsonWebKeys", - "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.get_aws_json_web_keys", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsJsonWebKeys", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GetAwsJsonWebKeys" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAwsJsonWebKeysRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AwsJsonWebKeys", - "shortName": "get_aws_json_web_keys" - }, - "description": "Sample for GetAwsJsonWebKeys", - "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsJsonWebKeys_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_json_web_keys_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.get_aws_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GetAwsNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAwsNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AwsNodePool", - "shortName": "get_aws_node_pool" - }, - "description": "Sample for GetAwsNodePool", - "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.get_aws_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GetAwsNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAwsNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AwsNodePool", - "shortName": "get_aws_node_pool" - }, - "description": "Sample for GetAwsNodePool", - "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.get_aws_open_id_config", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsOpenIdConfig", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GetAwsOpenIdConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAwsOpenIdConfigRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AwsOpenIdConfig", - "shortName": "get_aws_open_id_config" - }, - "description": "Sample for GetAwsOpenIdConfig", - "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.get_aws_open_id_config", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsOpenIdConfig", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GetAwsOpenIdConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAwsOpenIdConfigRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AwsOpenIdConfig", - "shortName": "get_aws_open_id_config" - }, - "description": "Sample for GetAwsOpenIdConfig", - "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsOpenIdConfig_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_open_id_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.get_aws_server_config", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsServerConfig", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GetAwsServerConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAwsServerConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AwsServerConfig", - "shortName": "get_aws_server_config" - }, - "description": "Sample for GetAwsServerConfig", - "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.get_aws_server_config", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.GetAwsServerConfig", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "GetAwsServerConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAwsServerConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AwsServerConfig", - "shortName": "get_aws_server_config" - }, - "description": "Sample for GetAwsServerConfig", - "file": "gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_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": "gkemulticloud_v1_generated_aws_clusters_get_aws_server_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.list_aws_clusters", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.ListAwsClusters", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "ListAwsClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsClustersAsyncPager", - "shortName": "list_aws_clusters" - }, - "description": "Sample for ListAwsClusters", - "file": "gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_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": "gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.list_aws_clusters", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.ListAwsClusters", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "ListAwsClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAwsClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsClustersPager", - "shortName": "list_aws_clusters" - }, - "description": "Sample for ListAwsClusters", - "file": "gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_ListAwsClusters_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": "gkemulticloud_v1_generated_aws_clusters_list_aws_clusters_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.list_aws_node_pools", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.ListAwsNodePools", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "ListAwsNodePools" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsNodePoolsAsyncPager", - "shortName": "list_aws_node_pools" - }, - "description": "Sample for ListAwsNodePools", - "file": "gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_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": "gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.list_aws_node_pools", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.ListAwsNodePools", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "ListAwsNodePools" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAwsNodePoolsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.aws_clusters.pagers.ListAwsNodePoolsPager", - "shortName": "list_aws_node_pools" - }, - "description": "Sample for ListAwsNodePools", - "file": "gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_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": "gkemulticloud_v1_generated_aws_clusters_list_aws_node_pools_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.rollback_aws_node_pool_update", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.RollbackAwsNodePoolUpdate", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "RollbackAwsNodePoolUpdate" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.RollbackAwsNodePoolUpdateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "rollback_aws_node_pool_update" - }, - "description": "Sample for RollbackAwsNodePoolUpdate", - "file": "gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_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": "gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.rollback_aws_node_pool_update", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.RollbackAwsNodePoolUpdate", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "RollbackAwsNodePoolUpdate" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.RollbackAwsNodePoolUpdateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "rollback_aws_node_pool_update" - }, - "description": "Sample for RollbackAwsNodePoolUpdate", - "file": "gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_RollbackAwsNodePoolUpdate_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": "gkemulticloud_v1_generated_aws_clusters_rollback_aws_node_pool_update_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.update_aws_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.UpdateAwsCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "UpdateAwsCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.UpdateAwsClusterRequest" - }, - { - "name": "aws_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AwsCluster" - }, - { - "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, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_aws_cluster" - }, - "description": "Sample for UpdateAwsCluster", - "file": "gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_async", - "segments": [ - { - "end": 68, - "start": 27, - "type": "FULL" - }, - { - "end": 68, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 58, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 65, - "start": 59, - "type": "REQUEST_EXECUTION" - }, - { - "end": 69, - "start": 66, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.update_aws_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.UpdateAwsCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "UpdateAwsCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.UpdateAwsClusterRequest" - }, - { - "name": "aws_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AwsCluster" - }, - { - "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, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_aws_cluster" - }, - "description": "Sample for UpdateAwsCluster", - "file": "gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_UpdateAwsCluster_sync", - "segments": [ - { - "end": 68, - "start": 27, - "type": "FULL" - }, - { - "end": 68, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 58, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 65, - "start": 59, - "type": "REQUEST_EXECUTION" - }, - { - "end": 69, - "start": 66, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_aws_clusters_update_aws_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient", - "shortName": "AwsClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersAsyncClient.update_aws_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.UpdateAwsNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "UpdateAwsNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.UpdateAwsNodePoolRequest" - }, - { - "name": "aws_node_pool", - "type": "google.cloud.gke_multicloud_v1.types.AwsNodePool" - }, - { - "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, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_aws_node_pool" - }, - "description": "Sample for UpdateAwsNodePool", - "file": "gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_async", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient", - "shortName": "AwsClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AwsClustersClient.update_aws_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters.UpdateAwsNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AwsClusters", - "shortName": "AwsClusters" - }, - "shortName": "UpdateAwsNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.UpdateAwsNodePoolRequest" - }, - { - "name": "aws_node_pool", - "type": "google.cloud.gke_multicloud_v1.types.AwsNodePool" - }, - { - "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, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_aws_node_pool" - }, - "description": "Sample for UpdateAwsNodePool", - "file": "gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_sync", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_aws_clusters_update_aws_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.create_azure_client", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureClient", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "CreateAzureClient" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAzureClientRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "azure_client", - "type": "google.cloud.gke_multicloud_v1.types.AzureClient" - }, - { - "name": "azure_client_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_azure_client" - }, - "description": "Sample for CreateAzureClient", - "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_client_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.create_azure_client", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureClient", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "CreateAzureClient" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAzureClientRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "azure_client", - "type": "google.cloud.gke_multicloud_v1.types.AzureClient" - }, - { - "name": "azure_client_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_azure_client" - }, - "description": "Sample for CreateAzureClient", - "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureClient_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_client_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.create_azure_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "CreateAzureCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAzureClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "azure_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AzureCluster" - }, - { - "name": "azure_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_azure_cluster" - }, - "description": "Sample for CreateAzureCluster", - "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_async", - "segments": [ - { - "end": 67, - "start": 27, - "type": "FULL" - }, - { - "end": 67, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 57, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 64, - "start": 58, - "type": "REQUEST_EXECUTION" - }, - { - "end": 68, - "start": 65, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.create_azure_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "CreateAzureCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAzureClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "azure_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AzureCluster" - }, - { - "name": "azure_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_azure_cluster" - }, - "description": "Sample for CreateAzureCluster", - "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureCluster_sync", - "segments": [ - { - "end": 67, - "start": 27, - "type": "FULL" - }, - { - "end": 67, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 57, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 64, - "start": 58, - "type": "REQUEST_EXECUTION" - }, - { - "end": 68, - "start": 65, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.create_azure_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "CreateAzureNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAzureNodePoolRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "azure_node_pool", - "type": "google.cloud.gke_multicloud_v1.types.AzureNodePool" - }, - { - "name": "azure_node_pool_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_azure_node_pool" - }, - "description": "Sample for CreateAzureNodePool", - "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_async", - "segments": [ - { - "end": 65, - "start": 27, - "type": "FULL" - }, - { - "end": 65, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 62, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 66, - "start": 63, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.create_azure_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.CreateAzureNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "CreateAzureNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.CreateAzureNodePoolRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "azure_node_pool", - "type": "google.cloud.gke_multicloud_v1.types.AzureNodePool" - }, - { - "name": "azure_node_pool_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_azure_node_pool" - }, - "description": "Sample for CreateAzureNodePool", - "file": "gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_sync", - "segments": [ - { - "end": 65, - "start": 27, - "type": "FULL" - }, - { - "end": 65, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 62, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 66, - "start": 63, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_create_azure_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.delete_azure_client", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureClient", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "DeleteAzureClient" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureClientRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_azure_client" - }, - "description": "Sample for DeleteAzureClient", - "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_client_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.delete_azure_client", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureClient", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "DeleteAzureClient" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureClientRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_azure_client" - }, - "description": "Sample for DeleteAzureClient", - "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_client_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.delete_azure_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "DeleteAzureCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_azure_cluster" - }, - "description": "Sample for DeleteAzureCluster", - "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.delete_azure_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "DeleteAzureCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_azure_cluster" - }, - "description": "Sample for DeleteAzureCluster", - "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.delete_azure_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "DeleteAzureNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_azure_node_pool" - }, - "description": "Sample for DeleteAzureNodePool", - "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.delete_azure_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.DeleteAzureNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "DeleteAzureNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.DeleteAzureNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_azure_node_pool" - }, - "description": "Sample for DeleteAzureNodePool", - "file": "gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_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": "gkemulticloud_v1_generated_azure_clusters_delete_azure_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.generate_azure_access_token", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GenerateAzureAccessToken", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GenerateAzureAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenResponse", - "shortName": "generate_azure_access_token" - }, - "description": "Sample for GenerateAzureAccessToken", - "file": "gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_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": "gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.generate_azure_access_token", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GenerateAzureAccessToken", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GenerateAzureAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAzureAccessTokenResponse", - "shortName": "generate_azure_access_token" - }, - "description": "Sample for GenerateAzureAccessToken", - "file": "gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_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": "gkemulticloud_v1_generated_azure_clusters_generate_azure_access_token_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.generate_azure_cluster_agent_token", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GenerateAzureClusterAgentToken", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GenerateAzureClusterAgentToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenResponse", - "shortName": "generate_azure_cluster_agent_token" - }, - "description": "Sample for GenerateAzureClusterAgentToken", - "file": "gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.generate_azure_cluster_agent_token", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GenerateAzureClusterAgentToken", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GenerateAzureClusterAgentToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.GenerateAzureClusterAgentTokenResponse", - "shortName": "generate_azure_cluster_agent_token" - }, - "description": "Sample for GenerateAzureClusterAgentToken", - "file": "gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GenerateAzureClusterAgentToken_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_generate_azure_cluster_agent_token_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_client", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureClient", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureClient" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureClientRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureClient", - "shortName": "get_azure_client" - }, - "description": "Sample for GetAzureClient", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureClient_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_client_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_client", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureClient", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureClient" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureClientRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureClient", - "shortName": "get_azure_client" - }, - "description": "Sample for GetAzureClient", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureClient_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_client_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureCluster", - "shortName": "get_azure_cluster" - }, - "description": "Sample for GetAzureCluster", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureCluster", - "shortName": "get_azure_cluster" - }, - "description": "Sample for GetAzureCluster", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_json_web_keys", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureJsonWebKeys", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureJsonWebKeys" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureJsonWebKeysRequest" - }, - { - "name": "azure_cluster", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureJsonWebKeys", - "shortName": "get_azure_json_web_keys" - }, - "description": "Sample for GetAzureJsonWebKeys", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_json_web_keys", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureJsonWebKeys", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureJsonWebKeys" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureJsonWebKeysRequest" - }, - { - "name": "azure_cluster", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureJsonWebKeys", - "shortName": "get_azure_json_web_keys" - }, - "description": "Sample for GetAzureJsonWebKeys", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureJsonWebKeys_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_json_web_keys_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureNodePool", - "shortName": "get_azure_node_pool" - }, - "description": "Sample for GetAzureNodePool", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureNodePool", - "shortName": "get_azure_node_pool" - }, - "description": "Sample for GetAzureNodePool", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_open_id_config", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureOpenIdConfig", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureOpenIdConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureOpenIdConfigRequest" - }, - { - "name": "azure_cluster", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureOpenIdConfig", - "shortName": "get_azure_open_id_config" - }, - "description": "Sample for GetAzureOpenIdConfig", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_open_id_config", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureOpenIdConfig", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureOpenIdConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureOpenIdConfigRequest" - }, - { - "name": "azure_cluster", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureOpenIdConfig", - "shortName": "get_azure_open_id_config" - }, - "description": "Sample for GetAzureOpenIdConfig", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureOpenIdConfig_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_open_id_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.get_azure_server_config", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureServerConfig", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureServerConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureServerConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureServerConfig", - "shortName": "get_azure_server_config" - }, - "description": "Sample for GetAzureServerConfig", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.get_azure_server_config", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.GetAzureServerConfig", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "GetAzureServerConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.GetAzureServerConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.types.AzureServerConfig", - "shortName": "get_azure_server_config" - }, - "description": "Sample for GetAzureServerConfig", - "file": "gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_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": "gkemulticloud_v1_generated_azure_clusters_get_azure_server_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.list_azure_clients", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClients", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "ListAzureClients" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClientsAsyncPager", - "shortName": "list_azure_clients" - }, - "description": "Sample for ListAzureClients", - "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureClients_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_clients_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.list_azure_clients", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClients", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "ListAzureClients" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAzureClientsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClientsPager", - "shortName": "list_azure_clients" - }, - "description": "Sample for ListAzureClients", - "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureClients_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_clients_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.list_azure_clusters", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClusters", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "ListAzureClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClustersAsyncPager", - "shortName": "list_azure_clusters" - }, - "description": "Sample for ListAzureClusters", - "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.list_azure_clusters", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureClusters", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "ListAzureClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAzureClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureClustersPager", - "shortName": "list_azure_clusters" - }, - "description": "Sample for ListAzureClusters", - "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_clusters_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.list_azure_node_pools", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureNodePools", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "ListAzureNodePools" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureNodePoolsAsyncPager", - "shortName": "list_azure_node_pools" - }, - "description": "Sample for ListAzureNodePools", - "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.list_azure_node_pools", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.ListAzureNodePools", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "ListAzureNodePools" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.ListAzureNodePoolsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.gke_multicloud_v1.services.azure_clusters.pagers.ListAzureNodePoolsPager", - "shortName": "list_azure_node_pools" - }, - "description": "Sample for ListAzureNodePools", - "file": "gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_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": "gkemulticloud_v1_generated_azure_clusters_list_azure_node_pools_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.update_azure_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.UpdateAzureCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "UpdateAzureCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.UpdateAzureClusterRequest" - }, - { - "name": "azure_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AzureCluster" - }, - { - "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, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_azure_cluster" - }, - "description": "Sample for UpdateAzureCluster", - "file": "gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_async", - "segments": [ - { - "end": 65, - "start": 27, - "type": "FULL" - }, - { - "end": 65, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 62, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 66, - "start": 63, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.update_azure_cluster", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.UpdateAzureCluster", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "UpdateAzureCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.UpdateAzureClusterRequest" - }, - { - "name": "azure_cluster", - "type": "google.cloud.gke_multicloud_v1.types.AzureCluster" - }, - { - "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, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_azure_cluster" - }, - "description": "Sample for UpdateAzureCluster", - "file": "gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_UpdateAzureCluster_sync", - "segments": [ - { - "end": 65, - "start": 27, - "type": "FULL" - }, - { - "end": 65, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 62, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 66, - "start": 63, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_update_azure_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient", - "shortName": "AzureClustersAsyncClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersAsyncClient.update_azure_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.UpdateAzureNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "UpdateAzureNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.UpdateAzureNodePoolRequest" - }, - { - "name": "azure_node_pool", - "type": "google.cloud.gke_multicloud_v1.types.AzureNodePool" - }, - { - "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, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_azure_node_pool" - }, - "description": "Sample for UpdateAzureNodePool", - "file": "gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_async", - "segments": [ - { - "end": 63, - "start": 27, - "type": "FULL" - }, - { - "end": 63, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 53, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 60, - "start": 54, - "type": "REQUEST_EXECUTION" - }, - { - "end": 64, - "start": 61, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient", - "shortName": "AzureClustersClient" - }, - "fullName": "google.cloud.gke_multicloud_v1.AzureClustersClient.update_azure_node_pool", - "method": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters.UpdateAzureNodePool", - "service": { - "fullName": "google.cloud.gkemulticloud.v1.AzureClusters", - "shortName": "AzureClusters" - }, - "shortName": "UpdateAzureNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.gke_multicloud_v1.types.UpdateAzureNodePoolRequest" - }, - { - "name": "azure_node_pool", - "type": "google.cloud.gke_multicloud_v1.types.AzureNodePool" - }, - { - "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, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_azure_node_pool" - }, - "description": "Sample for UpdateAzureNodePool", - "file": "gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_sync", - "segments": [ - { - "end": 63, - "start": 27, - "type": "FULL" - }, - { - "end": 63, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 53, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 60, - "start": 54, - "type": "REQUEST_EXECUTION" - }, - { - "end": 64, - "start": 61, - "type": "RESPONSE_HANDLING" - } - ], - "title": "gkemulticloud_v1_generated_azure_clusters_update_azure_node_pool_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/scripts/fixup_gke_multicloud_v1_keywords.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/scripts/fixup_gke_multicloud_v1_keywords.py deleted file mode 100644 index cd48868cf598..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/scripts/fixup_gke_multicloud_v1_keywords.py +++ /dev/null @@ -1,219 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class gke_multicloudCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_attached_cluster': ('parent', 'attached_cluster', 'attached_cluster_id', 'validate_only', ), - 'create_aws_cluster': ('parent', 'aws_cluster', 'aws_cluster_id', 'validate_only', ), - 'create_aws_node_pool': ('parent', 'aws_node_pool', 'aws_node_pool_id', 'validate_only', ), - 'create_azure_client': ('parent', 'azure_client', 'azure_client_id', 'validate_only', ), - 'create_azure_cluster': ('parent', 'azure_cluster', 'azure_cluster_id', 'validate_only', ), - 'create_azure_node_pool': ('parent', 'azure_node_pool', 'azure_node_pool_id', 'validate_only', ), - 'delete_attached_cluster': ('name', 'validate_only', 'allow_missing', 'ignore_errors', 'etag', ), - 'delete_aws_cluster': ('name', 'validate_only', 'allow_missing', 'ignore_errors', 'etag', ), - 'delete_aws_node_pool': ('name', 'validate_only', 'allow_missing', 'ignore_errors', 'etag', ), - 'delete_azure_client': ('name', 'allow_missing', 'validate_only', ), - 'delete_azure_cluster': ('name', 'allow_missing', 'validate_only', 'etag', 'ignore_errors', ), - 'delete_azure_node_pool': ('name', 'validate_only', 'allow_missing', 'etag', 'ignore_errors', ), - 'generate_attached_cluster_agent_token': ('attached_cluster', 'subject_token', 'subject_token_type', 'version', 'grant_type', 'audience', 'scope', 'requested_token_type', 'options', ), - 'generate_attached_cluster_install_manifest': ('parent', 'attached_cluster_id', 'platform_version', 'proxy_config', ), - 'generate_aws_access_token': ('aws_cluster', ), - 'generate_aws_cluster_agent_token': ('aws_cluster', 'subject_token', 'subject_token_type', 'version', 'node_pool_id', 'grant_type', 'audience', 'scope', 'requested_token_type', 'options', ), - 'generate_azure_access_token': ('azure_cluster', ), - 'generate_azure_cluster_agent_token': ('azure_cluster', 'subject_token', 'subject_token_type', 'version', 'node_pool_id', 'grant_type', 'audience', 'scope', 'requested_token_type', 'options', ), - 'get_attached_cluster': ('name', ), - 'get_attached_server_config': ('name', ), - 'get_aws_cluster': ('name', ), - 'get_aws_json_web_keys': ('aws_cluster', ), - 'get_aws_node_pool': ('name', ), - 'get_aws_open_id_config': ('aws_cluster', ), - 'get_aws_server_config': ('name', ), - 'get_azure_client': ('name', ), - 'get_azure_cluster': ('name', ), - 'get_azure_json_web_keys': ('azure_cluster', ), - 'get_azure_node_pool': ('name', ), - 'get_azure_open_id_config': ('azure_cluster', ), - 'get_azure_server_config': ('name', ), - 'import_attached_cluster': ('parent', 'fleet_membership', 'platform_version', 'distribution', 'validate_only', 'proxy_config', ), - 'list_attached_clusters': ('parent', 'page_size', 'page_token', ), - 'list_aws_clusters': ('parent', 'page_size', 'page_token', ), - 'list_aws_node_pools': ('parent', 'page_size', 'page_token', ), - 'list_azure_clients': ('parent', 'page_size', 'page_token', ), - 'list_azure_clusters': ('parent', 'page_size', 'page_token', ), - 'list_azure_node_pools': ('parent', 'page_size', 'page_token', ), - 'rollback_aws_node_pool_update': ('name', 'respect_pdb', ), - 'update_attached_cluster': ('attached_cluster', 'update_mask', 'validate_only', ), - 'update_aws_cluster': ('aws_cluster', 'update_mask', 'validate_only', ), - 'update_aws_node_pool': ('aws_node_pool', 'update_mask', 'validate_only', ), - 'update_azure_cluster': ('azure_cluster', 'update_mask', 'validate_only', ), - 'update_azure_node_pool': ('azure_node_pool', 'update_mask', 'validate_only', ), - } - - 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=gke_multicloudCallTransformer(), -): - """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 gke_multicloud client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/setup.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/setup.py deleted file mode 100644 index e3eb68074546..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/setup.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-gke-multicloud' - - -description = "Google Cloud Gke Multicloud API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/gke_multicloud/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-multicloud" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/__init__.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_attached_clusters.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_attached_clusters.py deleted file mode 100644 index e446f56b4f3f..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_attached_clusters.py +++ /dev/null @@ -1,8616 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.gke_multicloud_v1.services.attached_clusters import AttachedClustersAsyncClient -from google.cloud.gke_multicloud_v1.services.attached_clusters import AttachedClustersClient -from google.cloud.gke_multicloud_v1.services.attached_clusters import pagers -from google.cloud.gke_multicloud_v1.services.attached_clusters import transports -from google.cloud.gke_multicloud_v1.types import attached_resources -from google.cloud.gke_multicloud_v1.types import attached_service -from google.cloud.gke_multicloud_v1.types import common_resources -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 - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AttachedClustersClient._get_default_mtls_endpoint(None) is None - assert AttachedClustersClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AttachedClustersClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AttachedClustersClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AttachedClustersClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AttachedClustersClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AttachedClustersClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AttachedClustersClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AttachedClustersClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AttachedClustersClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert AttachedClustersClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AttachedClustersClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AttachedClustersClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AttachedClustersClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert AttachedClustersClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert AttachedClustersClient._get_client_cert_source(None, False) is None - assert AttachedClustersClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AttachedClustersClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert AttachedClustersClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AttachedClustersClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AttachedClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersClient)) -@mock.patch.object(AttachedClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AttachedClustersClient._DEFAULT_UNIVERSE - default_endpoint = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AttachedClustersClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AttachedClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AttachedClustersClient.DEFAULT_MTLS_ENDPOINT - assert AttachedClustersClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AttachedClustersClient._get_api_endpoint(None, None, default_universe, "always") == AttachedClustersClient.DEFAULT_MTLS_ENDPOINT - assert AttachedClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AttachedClustersClient.DEFAULT_MTLS_ENDPOINT - assert AttachedClustersClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AttachedClustersClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AttachedClustersClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert AttachedClustersClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AttachedClustersClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AttachedClustersClient._get_universe_domain(None, None) == AttachedClustersClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AttachedClustersClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AttachedClustersClient, "grpc"), - (AttachedClustersAsyncClient, "grpc_asyncio"), - (AttachedClustersClient, "rest"), -]) -def test_attached_clusters_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 == ( - 'gkemulticloud.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://gkemulticloud.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AttachedClustersGrpcTransport, "grpc"), - (transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AttachedClustersRestTransport, "rest"), -]) -def test_attached_clusters_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", [ - (AttachedClustersClient, "grpc"), - (AttachedClustersAsyncClient, "grpc_asyncio"), - (AttachedClustersClient, "rest"), -]) -def test_attached_clusters_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 == ( - 'gkemulticloud.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://gkemulticloud.googleapis.com' - ) - - -def test_attached_clusters_client_get_transport_class(): - transport = AttachedClustersClient.get_transport_class() - available_transports = [ - transports.AttachedClustersGrpcTransport, - transports.AttachedClustersRestTransport, - ] - assert transport in available_transports - - transport = AttachedClustersClient.get_transport_class("grpc") - assert transport == transports.AttachedClustersGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc"), - (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio"), - (AttachedClustersClient, transports.AttachedClustersRestTransport, "rest"), -]) -@mock.patch.object(AttachedClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersClient)) -@mock.patch.object(AttachedClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersAsyncClient)) -def test_attached_clusters_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(AttachedClustersClient, '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(AttachedClustersClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc", "true"), - (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc", "false"), - (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AttachedClustersClient, transports.AttachedClustersRestTransport, "rest", "true"), - (AttachedClustersClient, transports.AttachedClustersRestTransport, "rest", "false"), -]) -@mock.patch.object(AttachedClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersClient)) -@mock.patch.object(AttachedClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_attached_clusters_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - AttachedClustersClient, AttachedClustersAsyncClient -]) -@mock.patch.object(AttachedClustersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AttachedClustersClient)) -@mock.patch.object(AttachedClustersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AttachedClustersAsyncClient)) -def test_attached_clusters_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - AttachedClustersClient, AttachedClustersAsyncClient -]) -@mock.patch.object(AttachedClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersClient)) -@mock.patch.object(AttachedClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AttachedClustersAsyncClient)) -def test_attached_clusters_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AttachedClustersClient._DEFAULT_UNIVERSE - default_endpoint = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AttachedClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc"), - (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio"), - (AttachedClustersClient, transports.AttachedClustersRestTransport, "rest"), -]) -def test_attached_clusters_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc", grpc_helpers), - (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AttachedClustersClient, transports.AttachedClustersRestTransport, "rest", None), -]) -def test_attached_clusters_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_attached_clusters_client_client_options_from_dict(): - with mock.patch('google.cloud.gke_multicloud_v1.services.attached_clusters.transports.AttachedClustersGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AttachedClustersClient( - 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", [ - (AttachedClustersClient, transports.AttachedClustersGrpcTransport, "grpc", grpc_helpers), - (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_attached_clusters_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "gkemulticloud.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="gkemulticloud.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - attached_service.CreateAttachedClusterRequest, - dict, -]) -def test_create_attached_cluster(request_type, transport: str = 'grpc'): - client = AttachedClustersClient( - 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_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = attached_service.CreateAttachedClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_attached_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = attached_service.CreateAttachedClusterRequest( - parent='parent_value', - attached_cluster_id='attached_cluster_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_attached_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_attached_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == attached_service.CreateAttachedClusterRequest( - parent='parent_value', - attached_cluster_id='attached_cluster_id_value', - ) - -def test_create_attached_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_attached_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_attached_cluster] = mock_rpc - request = {} - client.create_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_attached_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_attached_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_attached_cluster] = mock_rpc - - request = {} - await client.create_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_attached_cluster_async(transport: str = 'grpc_asyncio', request_type=attached_service.CreateAttachedClusterRequest): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_attached_cluster), - '__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_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = attached_service.CreateAttachedClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_attached_cluster_async_from_dict(): - await test_create_attached_cluster_async(request_type=dict) - -def test_create_attached_cluster_field_headers(): - client = AttachedClustersClient( - 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 = attached_service.CreateAttachedClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_attached_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_attached_cluster(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_attached_cluster_field_headers_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = attached_service.CreateAttachedClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_attached_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_attached_cluster(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_attached_cluster_flattened(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_attached_cluster), - '__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_attached_cluster( - parent='parent_value', - attached_cluster=attached_resources.AttachedCluster(name='name_value'), - attached_cluster_id='attached_cluster_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].attached_cluster - mock_val = attached_resources.AttachedCluster(name='name_value') - assert arg == mock_val - arg = args[0].attached_cluster_id - mock_val = 'attached_cluster_id_value' - assert arg == mock_val - - -def test_create_attached_cluster_flattened_error(): - client = AttachedClustersClient( - 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_attached_cluster( - attached_service.CreateAttachedClusterRequest(), - parent='parent_value', - attached_cluster=attached_resources.AttachedCluster(name='name_value'), - attached_cluster_id='attached_cluster_id_value', - ) - -@pytest.mark.asyncio -async def test_create_attached_cluster_flattened_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_attached_cluster), - '__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_attached_cluster( - parent='parent_value', - attached_cluster=attached_resources.AttachedCluster(name='name_value'), - attached_cluster_id='attached_cluster_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].attached_cluster - mock_val = attached_resources.AttachedCluster(name='name_value') - assert arg == mock_val - arg = args[0].attached_cluster_id - mock_val = 'attached_cluster_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_attached_cluster_flattened_error_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_attached_cluster( - attached_service.CreateAttachedClusterRequest(), - parent='parent_value', - attached_cluster=attached_resources.AttachedCluster(name='name_value'), - attached_cluster_id='attached_cluster_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - attached_service.UpdateAttachedClusterRequest, - dict, -]) -def test_update_attached_cluster(request_type, transport: str = 'grpc'): - client = AttachedClustersClient( - 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_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = attached_service.UpdateAttachedClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_attached_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = attached_service.UpdateAttachedClusterRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attached_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_attached_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == attached_service.UpdateAttachedClusterRequest( - ) - -def test_update_attached_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_attached_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_attached_cluster] = mock_rpc - request = {} - client.update_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_attached_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_attached_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_attached_cluster] = mock_rpc - - request = {} - await client.update_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_attached_cluster_async(transport: str = 'grpc_asyncio', request_type=attached_service.UpdateAttachedClusterRequest): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_attached_cluster), - '__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_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = attached_service.UpdateAttachedClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_attached_cluster_async_from_dict(): - await test_update_attached_cluster_async(request_type=dict) - -def test_update_attached_cluster_field_headers(): - client = AttachedClustersClient( - 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 = attached_service.UpdateAttachedClusterRequest() - - request.attached_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attached_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_attached_cluster(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', - 'attached_cluster.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_attached_cluster_field_headers_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = attached_service.UpdateAttachedClusterRequest() - - request.attached_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attached_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_attached_cluster(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', - 'attached_cluster.name=name_value', - ) in kw['metadata'] - - -def test_update_attached_cluster_flattened(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attached_cluster), - '__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_attached_cluster( - attached_cluster=attached_resources.AttachedCluster(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].attached_cluster - mock_val = attached_resources.AttachedCluster(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_attached_cluster_flattened_error(): - client = AttachedClustersClient( - 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_attached_cluster( - attached_service.UpdateAttachedClusterRequest(), - attached_cluster=attached_resources.AttachedCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_attached_cluster_flattened_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attached_cluster), - '__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_attached_cluster( - attached_cluster=attached_resources.AttachedCluster(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].attached_cluster - mock_val = attached_resources.AttachedCluster(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_attached_cluster_flattened_error_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_attached_cluster( - attached_service.UpdateAttachedClusterRequest(), - attached_cluster=attached_resources.AttachedCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - attached_service.ImportAttachedClusterRequest, - dict, -]) -def test_import_attached_cluster(request_type, transport: str = 'grpc'): - client = AttachedClustersClient( - 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.import_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = attached_service.ImportAttachedClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_attached_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = attached_service.ImportAttachedClusterRequest( - parent='parent_value', - fleet_membership='fleet_membership_value', - platform_version='platform_version_value', - distribution='distribution_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_attached_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.import_attached_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == attached_service.ImportAttachedClusterRequest( - parent='parent_value', - fleet_membership='fleet_membership_value', - platform_version='platform_version_value', - distribution='distribution_value', - ) - -def test_import_attached_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.import_attached_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.import_attached_cluster] = mock_rpc - request = {} - client.import_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.import_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_import_attached_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.import_attached_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.import_attached_cluster] = mock_rpc - - request = {} - await client.import_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.import_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_import_attached_cluster_async(transport: str = 'grpc_asyncio', request_type=attached_service.ImportAttachedClusterRequest): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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.import_attached_cluster), - '__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.import_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = attached_service.ImportAttachedClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_attached_cluster_async_from_dict(): - await test_import_attached_cluster_async(request_type=dict) - -def test_import_attached_cluster_field_headers(): - client = AttachedClustersClient( - 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 = attached_service.ImportAttachedClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_attached_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_attached_cluster(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_import_attached_cluster_field_headers_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = attached_service.ImportAttachedClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_attached_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_attached_cluster(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_import_attached_cluster_flattened(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_attached_cluster), - '__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.import_attached_cluster( - parent='parent_value', - fleet_membership='fleet_membership_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].fleet_membership - mock_val = 'fleet_membership_value' - assert arg == mock_val - - -def test_import_attached_cluster_flattened_error(): - client = AttachedClustersClient( - 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.import_attached_cluster( - attached_service.ImportAttachedClusterRequest(), - parent='parent_value', - fleet_membership='fleet_membership_value', - ) - -@pytest.mark.asyncio -async def test_import_attached_cluster_flattened_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_attached_cluster), - '__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.import_attached_cluster( - parent='parent_value', - fleet_membership='fleet_membership_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].fleet_membership - mock_val = 'fleet_membership_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_import_attached_cluster_flattened_error_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.import_attached_cluster( - attached_service.ImportAttachedClusterRequest(), - parent='parent_value', - fleet_membership='fleet_membership_value', - ) - - -@pytest.mark.parametrize("request_type", [ - attached_service.GetAttachedClusterRequest, - dict, -]) -def test_get_attached_cluster(request_type, transport: str = 'grpc'): - client = AttachedClustersClient( - 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_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_resources.AttachedCluster( - name='name_value', - description='description_value', - platform_version='platform_version_value', - distribution='distribution_value', - cluster_region='cluster_region_value', - state=attached_resources.AttachedCluster.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - kubernetes_version='kubernetes_version_value', - ) - response = client.get_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = attached_service.GetAttachedClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_resources.AttachedCluster) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.platform_version == 'platform_version_value' - assert response.distribution == 'distribution_value' - assert response.cluster_region == 'cluster_region_value' - assert response.state == attached_resources.AttachedCluster.State.PROVISIONING - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.kubernetes_version == 'kubernetes_version_value' - - -def test_get_attached_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = attached_service.GetAttachedClusterRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_attached_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == attached_service.GetAttachedClusterRequest( - name='name_value', - ) - -def test_get_attached_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_attached_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_attached_cluster] = mock_rpc - request = {} - client.get_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_attached_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_attached_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_attached_cluster] = mock_rpc - - request = {} - await client.get_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_attached_cluster_async(transport: str = 'grpc_asyncio', request_type=attached_service.GetAttachedClusterRequest): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedCluster( - name='name_value', - description='description_value', - platform_version='platform_version_value', - distribution='distribution_value', - cluster_region='cluster_region_value', - state=attached_resources.AttachedCluster.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - kubernetes_version='kubernetes_version_value', - )) - response = await client.get_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = attached_service.GetAttachedClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_resources.AttachedCluster) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.platform_version == 'platform_version_value' - assert response.distribution == 'distribution_value' - assert response.cluster_region == 'cluster_region_value' - assert response.state == attached_resources.AttachedCluster.State.PROVISIONING - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.kubernetes_version == 'kubernetes_version_value' - - -@pytest.mark.asyncio -async def test_get_attached_cluster_async_from_dict(): - await test_get_attached_cluster_async(request_type=dict) - -def test_get_attached_cluster_field_headers(): - client = AttachedClustersClient( - 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 = attached_service.GetAttachedClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_cluster), - '__call__') as call: - call.return_value = attached_resources.AttachedCluster() - client.get_attached_cluster(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_attached_cluster_field_headers_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = attached_service.GetAttachedClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedCluster()) - await client.get_attached_cluster(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_attached_cluster_flattened(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_resources.AttachedCluster() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_attached_cluster( - 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_attached_cluster_flattened_error(): - client = AttachedClustersClient( - 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_attached_cluster( - attached_service.GetAttachedClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_attached_cluster_flattened_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_resources.AttachedCluster() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedCluster()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_attached_cluster( - 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_attached_cluster_flattened_error_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_attached_cluster( - attached_service.GetAttachedClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - attached_service.ListAttachedClustersRequest, - dict, -]) -def test_list_attached_clusters(request_type, transport: str = 'grpc'): - client = AttachedClustersClient( - 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_attached_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_service.ListAttachedClustersResponse( - next_page_token='next_page_token_value', - ) - response = client.list_attached_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = attached_service.ListAttachedClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttachedClustersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_attached_clusters_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = attached_service.ListAttachedClustersRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attached_clusters), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_attached_clusters(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == attached_service.ListAttachedClustersRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_attached_clusters_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_attached_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_attached_clusters] = mock_rpc - request = {} - client.list_attached_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_attached_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_attached_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_attached_clusters in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_attached_clusters] = mock_rpc - - request = {} - await client.list_attached_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_attached_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_attached_clusters_async(transport: str = 'grpc_asyncio', request_type=attached_service.ListAttachedClustersRequest): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_attached_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attached_service.ListAttachedClustersResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_attached_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = attached_service.ListAttachedClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttachedClustersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_attached_clusters_async_from_dict(): - await test_list_attached_clusters_async(request_type=dict) - -def test_list_attached_clusters_field_headers(): - client = AttachedClustersClient( - 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 = attached_service.ListAttachedClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attached_clusters), - '__call__') as call: - call.return_value = attached_service.ListAttachedClustersResponse() - client.list_attached_clusters(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_attached_clusters_field_headers_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = attached_service.ListAttachedClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attached_clusters), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.ListAttachedClustersResponse()) - await client.list_attached_clusters(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_attached_clusters_flattened(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attached_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_service.ListAttachedClustersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_attached_clusters( - 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_attached_clusters_flattened_error(): - client = AttachedClustersClient( - 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_attached_clusters( - attached_service.ListAttachedClustersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_attached_clusters_flattened_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attached_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_service.ListAttachedClustersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.ListAttachedClustersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_attached_clusters( - 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_attached_clusters_flattened_error_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_attached_clusters( - attached_service.ListAttachedClustersRequest(), - parent='parent_value', - ) - - -def test_list_attached_clusters_pager(transport_name: str = "grpc"): - client = AttachedClustersClient( - 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_attached_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - ], - next_page_token='abc', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[], - next_page_token='def', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - ], - next_page_token='ghi', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_attached_clusters(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, attached_resources.AttachedCluster) - for i in results) -def test_list_attached_clusters_pages(transport_name: str = "grpc"): - client = AttachedClustersClient( - 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_attached_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - ], - next_page_token='abc', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[], - next_page_token='def', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - ], - next_page_token='ghi', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - ], - ), - RuntimeError, - ) - pages = list(client.list_attached_clusters(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_attached_clusters_async_pager(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attached_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - ], - next_page_token='abc', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[], - next_page_token='def', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - ], - next_page_token='ghi', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_attached_clusters(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, attached_resources.AttachedCluster) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_attached_clusters_async_pages(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attached_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - ], - next_page_token='abc', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[], - next_page_token='def', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - ], - next_page_token='ghi', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - ], - ), - 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_attached_clusters(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", [ - attached_service.DeleteAttachedClusterRequest, - dict, -]) -def test_delete_attached_cluster(request_type, transport: str = 'grpc'): - client = AttachedClustersClient( - 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_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = attached_service.DeleteAttachedClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_attached_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = attached_service.DeleteAttachedClusterRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_attached_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_attached_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == attached_service.DeleteAttachedClusterRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_attached_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_attached_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_attached_cluster] = mock_rpc - request = {} - client.delete_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_attached_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_attached_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_attached_cluster] = mock_rpc - - request = {} - await client.delete_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_attached_cluster_async(transport: str = 'grpc_asyncio', request_type=attached_service.DeleteAttachedClusterRequest): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_attached_cluster), - '__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_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = attached_service.DeleteAttachedClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_attached_cluster_async_from_dict(): - await test_delete_attached_cluster_async(request_type=dict) - -def test_delete_attached_cluster_field_headers(): - client = AttachedClustersClient( - 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 = attached_service.DeleteAttachedClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_attached_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_attached_cluster(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_attached_cluster_field_headers_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = attached_service.DeleteAttachedClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_attached_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_attached_cluster(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_attached_cluster_flattened(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_attached_cluster), - '__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_attached_cluster( - 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_attached_cluster_flattened_error(): - client = AttachedClustersClient( - 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_attached_cluster( - attached_service.DeleteAttachedClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_attached_cluster_flattened_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_attached_cluster), - '__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_attached_cluster( - 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_attached_cluster_flattened_error_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_attached_cluster( - attached_service.DeleteAttachedClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - attached_service.GetAttachedServerConfigRequest, - dict, -]) -def test_get_attached_server_config(request_type, transport: str = 'grpc'): - client = AttachedClustersClient( - 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_attached_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_resources.AttachedServerConfig( - name='name_value', - ) - response = client.get_attached_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = attached_service.GetAttachedServerConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_resources.AttachedServerConfig) - assert response.name == 'name_value' - - -def test_get_attached_server_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = attached_service.GetAttachedServerConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_server_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_attached_server_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == attached_service.GetAttachedServerConfigRequest( - name='name_value', - ) - -def test_get_attached_server_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_attached_server_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_attached_server_config] = mock_rpc - request = {} - client.get_attached_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_attached_server_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_attached_server_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_attached_server_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_attached_server_config] = mock_rpc - - request = {} - await client.get_attached_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_attached_server_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_attached_server_config_async(transport: str = 'grpc_asyncio', request_type=attached_service.GetAttachedServerConfigRequest): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_attached_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedServerConfig( - name='name_value', - )) - response = await client.get_attached_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = attached_service.GetAttachedServerConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_resources.AttachedServerConfig) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_attached_server_config_async_from_dict(): - await test_get_attached_server_config_async(request_type=dict) - -def test_get_attached_server_config_field_headers(): - client = AttachedClustersClient( - 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 = attached_service.GetAttachedServerConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_server_config), - '__call__') as call: - call.return_value = attached_resources.AttachedServerConfig() - client.get_attached_server_config(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_attached_server_config_field_headers_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = attached_service.GetAttachedServerConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_server_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedServerConfig()) - await client.get_attached_server_config(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_attached_server_config_flattened(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_resources.AttachedServerConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_attached_server_config( - 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_attached_server_config_flattened_error(): - client = AttachedClustersClient( - 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_attached_server_config( - attached_service.GetAttachedServerConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_attached_server_config_flattened_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_resources.AttachedServerConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedServerConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_attached_server_config( - 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_attached_server_config_flattened_error_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_attached_server_config( - attached_service.GetAttachedServerConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - attached_service.GenerateAttachedClusterInstallManifestRequest, - dict, -]) -def test_generate_attached_cluster_install_manifest(request_type, transport: str = 'grpc'): - client = AttachedClustersClient( - 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_attached_cluster_install_manifest), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse( - manifest='manifest_value', - ) - response = client.generate_attached_cluster_install_manifest(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = attached_service.GenerateAttachedClusterInstallManifestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_service.GenerateAttachedClusterInstallManifestResponse) - assert response.manifest == 'manifest_value' - - -def test_generate_attached_cluster_install_manifest_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = attached_service.GenerateAttachedClusterInstallManifestRequest( - parent='parent_value', - attached_cluster_id='attached_cluster_id_value', - platform_version='platform_version_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_install_manifest), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_attached_cluster_install_manifest(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == attached_service.GenerateAttachedClusterInstallManifestRequest( - parent='parent_value', - attached_cluster_id='attached_cluster_id_value', - platform_version='platform_version_value', - ) - -def test_generate_attached_cluster_install_manifest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_attached_cluster_install_manifest in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_attached_cluster_install_manifest] = mock_rpc - request = {} - client.generate_attached_cluster_install_manifest(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_attached_cluster_install_manifest(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_attached_cluster_install_manifest_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_attached_cluster_install_manifest in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_attached_cluster_install_manifest] = mock_rpc - - request = {} - await client.generate_attached_cluster_install_manifest(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_attached_cluster_install_manifest(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_attached_cluster_install_manifest_async(transport: str = 'grpc_asyncio', request_type=attached_service.GenerateAttachedClusterInstallManifestRequest): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_attached_cluster_install_manifest), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterInstallManifestResponse( - manifest='manifest_value', - )) - response = await client.generate_attached_cluster_install_manifest(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = attached_service.GenerateAttachedClusterInstallManifestRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_service.GenerateAttachedClusterInstallManifestResponse) - assert response.manifest == 'manifest_value' - - -@pytest.mark.asyncio -async def test_generate_attached_cluster_install_manifest_async_from_dict(): - await test_generate_attached_cluster_install_manifest_async(request_type=dict) - -def test_generate_attached_cluster_install_manifest_field_headers(): - client = AttachedClustersClient( - 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 = attached_service.GenerateAttachedClusterInstallManifestRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_install_manifest), - '__call__') as call: - call.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() - client.generate_attached_cluster_install_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_attached_cluster_install_manifest_field_headers_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = attached_service.GenerateAttachedClusterInstallManifestRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_install_manifest), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterInstallManifestResponse()) - await client.generate_attached_cluster_install_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_generate_attached_cluster_install_manifest_flattened(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_install_manifest), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_attached_cluster_install_manifest( - parent='parent_value', - attached_cluster_id='attached_cluster_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].attached_cluster_id - mock_val = 'attached_cluster_id_value' - assert arg == mock_val - - -def test_generate_attached_cluster_install_manifest_flattened_error(): - client = AttachedClustersClient( - 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.generate_attached_cluster_install_manifest( - attached_service.GenerateAttachedClusterInstallManifestRequest(), - parent='parent_value', - attached_cluster_id='attached_cluster_id_value', - ) - -@pytest.mark.asyncio -async def test_generate_attached_cluster_install_manifest_flattened_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_install_manifest), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterInstallManifestResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_attached_cluster_install_manifest( - parent='parent_value', - attached_cluster_id='attached_cluster_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].attached_cluster_id - mock_val = 'attached_cluster_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_generate_attached_cluster_install_manifest_flattened_error_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.generate_attached_cluster_install_manifest( - attached_service.GenerateAttachedClusterInstallManifestRequest(), - parent='parent_value', - attached_cluster_id='attached_cluster_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - attached_service.GenerateAttachedClusterAgentTokenRequest, - dict, -]) -def test_generate_attached_cluster_agent_token(request_type, transport: str = 'grpc'): - client = AttachedClustersClient( - 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_attached_cluster_agent_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = attached_service.GenerateAttachedClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - ) - response = client.generate_attached_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = attached_service.GenerateAttachedClusterAgentTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_service.GenerateAttachedClusterAgentTokenResponse) - assert response.access_token == 'access_token_value' - assert response.expires_in == 1078 - assert response.token_type == 'token_type_value' - - -def test_generate_attached_cluster_agent_token_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = attached_service.GenerateAttachedClusterAgentTokenRequest( - attached_cluster='attached_cluster_value', - subject_token='subject_token_value', - subject_token_type='subject_token_type_value', - version='version_value', - grant_type='grant_type_value', - audience='audience_value', - scope='scope_value', - requested_token_type='requested_token_type_value', - options='options_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_agent_token), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_attached_cluster_agent_token(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == attached_service.GenerateAttachedClusterAgentTokenRequest( - attached_cluster='attached_cluster_value', - subject_token='subject_token_value', - subject_token_type='subject_token_type_value', - version='version_value', - grant_type='grant_type_value', - audience='audience_value', - scope='scope_value', - requested_token_type='requested_token_type_value', - options='options_value', - ) - -def test_generate_attached_cluster_agent_token_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_attached_cluster_agent_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_attached_cluster_agent_token] = mock_rpc - request = {} - client.generate_attached_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_attached_cluster_agent_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_attached_cluster_agent_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_attached_cluster_agent_token in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_attached_cluster_agent_token] = mock_rpc - - request = {} - await client.generate_attached_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_attached_cluster_agent_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_attached_cluster_agent_token_async(transport: str = 'grpc_asyncio', request_type=attached_service.GenerateAttachedClusterAgentTokenRequest): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_attached_cluster_agent_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - )) - response = await client.generate_attached_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = attached_service.GenerateAttachedClusterAgentTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_service.GenerateAttachedClusterAgentTokenResponse) - assert response.access_token == 'access_token_value' - assert response.expires_in == 1078 - assert response.token_type == 'token_type_value' - - -@pytest.mark.asyncio -async def test_generate_attached_cluster_agent_token_async_from_dict(): - await test_generate_attached_cluster_agent_token_async(request_type=dict) - -def test_generate_attached_cluster_agent_token_field_headers(): - client = AttachedClustersClient( - 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 = attached_service.GenerateAttachedClusterAgentTokenRequest() - - request.attached_cluster = 'attached_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_agent_token), - '__call__') as call: - call.return_value = attached_service.GenerateAttachedClusterAgentTokenResponse() - client.generate_attached_cluster_agent_token(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', - 'attached_cluster=attached_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_attached_cluster_agent_token_field_headers_async(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = attached_service.GenerateAttachedClusterAgentTokenRequest() - - request.attached_cluster = 'attached_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_agent_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterAgentTokenResponse()) - await client.generate_attached_cluster_agent_token(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', - 'attached_cluster=attached_cluster_value', - ) in kw['metadata'] - - -def test_create_attached_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_attached_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_attached_cluster] = mock_rpc - - request = {} - client.create_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_attached_cluster_rest_required_fields(request_type=attached_service.CreateAttachedClusterRequest): - transport_class = transports.AttachedClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["attached_cluster_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "attachedClusterId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_attached_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "attachedClusterId" in jsonified_request - assert jsonified_request["attachedClusterId"] == request_init["attached_cluster_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["attachedClusterId"] = 'attached_cluster_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_attached_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("attached_cluster_id", "validate_only", )) - 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 "attachedClusterId" in jsonified_request - assert jsonified_request["attachedClusterId"] == 'attached_cluster_id_value' - - client = AttachedClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_attached_cluster(request) - - expected_params = [ - ( - "attachedClusterId", - "", - ), - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_attached_cluster_rest_unset_required_fields(): - transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_attached_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("attachedClusterId", "validateOnly", )) & set(("parent", "attachedCluster", "attachedClusterId", ))) - - -def test_create_attached_cluster_rest_flattened(): - client = AttachedClustersClient( - 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', - attached_cluster=attached_resources.AttachedCluster(name='name_value'), - attached_cluster_id='attached_cluster_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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_attached_cluster(**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/*}/attachedClusters" % client.transport._host, args[1]) - - -def test_create_attached_cluster_rest_flattened_error(transport: str = 'rest'): - client = AttachedClustersClient( - 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_attached_cluster( - attached_service.CreateAttachedClusterRequest(), - parent='parent_value', - attached_cluster=attached_resources.AttachedCluster(name='name_value'), - attached_cluster_id='attached_cluster_id_value', - ) - - -def test_update_attached_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_attached_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_attached_cluster] = mock_rpc - - request = {} - client.update_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_attached_cluster_rest_required_fields(request_type=attached_service.UpdateAttachedClusterRequest): - transport_class = transports.AttachedClustersRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_attached_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_attached_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AttachedClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_attached_cluster(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_attached_cluster_rest_unset_required_fields(): - transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_attached_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("attachedCluster", "updateMask", ))) - - -def test_update_attached_cluster_rest_flattened(): - client = AttachedClustersClient( - 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 = {'attached_cluster': {'name': 'projects/sample1/locations/sample2/attachedClusters/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - attached_cluster=attached_resources.AttachedCluster(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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_attached_cluster(**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/{attached_cluster.name=projects/*/locations/*/attachedClusters/*}" % client.transport._host, args[1]) - - -def test_update_attached_cluster_rest_flattened_error(transport: str = 'rest'): - client = AttachedClustersClient( - 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_attached_cluster( - attached_service.UpdateAttachedClusterRequest(), - attached_cluster=attached_resources.AttachedCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_import_attached_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.import_attached_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.import_attached_cluster] = mock_rpc - - request = {} - client.import_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.import_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_import_attached_cluster_rest_required_fields(request_type=attached_service.ImportAttachedClusterRequest): - transport_class = transports.AttachedClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["fleet_membership"] = "" - request_init["platform_version"] = "" - request_init["distribution"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_attached_cluster._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' - jsonified_request["fleetMembership"] = 'fleet_membership_value' - jsonified_request["platformVersion"] = 'platform_version_value' - jsonified_request["distribution"] = 'distribution_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_attached_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "fleetMembership" in jsonified_request - assert jsonified_request["fleetMembership"] == 'fleet_membership_value' - assert "platformVersion" in jsonified_request - assert jsonified_request["platformVersion"] == 'platform_version_value' - assert "distribution" in jsonified_request - assert jsonified_request["distribution"] == 'distribution_value' - - client = AttachedClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.import_attached_cluster(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_attached_cluster_rest_unset_required_fields(): - transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_attached_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "fleetMembership", "platformVersion", "distribution", ))) - - -def test_import_attached_cluster_rest_flattened(): - client = AttachedClustersClient( - 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', - fleet_membership='fleet_membership_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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.import_attached_cluster(**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/*}/attachedClusters:import" % client.transport._host, args[1]) - - -def test_import_attached_cluster_rest_flattened_error(transport: str = 'rest'): - client = AttachedClustersClient( - 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.import_attached_cluster( - attached_service.ImportAttachedClusterRequest(), - parent='parent_value', - fleet_membership='fleet_membership_value', - ) - - -def test_get_attached_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_attached_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_attached_cluster] = mock_rpc - - request = {} - client.get_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_attached_cluster_rest_required_fields(request_type=attached_service.GetAttachedClusterRequest): - transport_class = transports.AttachedClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_attached_cluster._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_attached_cluster._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 = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = attached_resources.AttachedCluster() - # 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 = attached_resources.AttachedCluster.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_attached_cluster(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_attached_cluster_rest_unset_required_fields(): - transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_attached_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_attached_cluster_rest_flattened(): - client = AttachedClustersClient( - 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 = attached_resources.AttachedCluster() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = attached_resources.AttachedCluster.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_attached_cluster(**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/*/attachedClusters/*}" % client.transport._host, args[1]) - - -def test_get_attached_cluster_rest_flattened_error(transport: str = 'rest'): - client = AttachedClustersClient( - 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_attached_cluster( - attached_service.GetAttachedClusterRequest(), - name='name_value', - ) - - -def test_list_attached_clusters_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_attached_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_attached_clusters] = mock_rpc - - request = {} - client.list_attached_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_attached_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_attached_clusters_rest_required_fields(request_type=attached_service.ListAttachedClustersRequest): - transport_class = transports.AttachedClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_attached_clusters._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_attached_clusters._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - 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 = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = attached_service.ListAttachedClustersResponse() - # 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 = attached_service.ListAttachedClustersResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_attached_clusters(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_attached_clusters_rest_unset_required_fields(): - transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_attached_clusters._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_attached_clusters_rest_flattened(): - client = AttachedClustersClient( - 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 = attached_service.ListAttachedClustersResponse() - - # 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 = attached_service.ListAttachedClustersResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_attached_clusters(**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/*}/attachedClusters" % client.transport._host, args[1]) - - -def test_list_attached_clusters_rest_flattened_error(transport: str = 'rest'): - client = AttachedClustersClient( - 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_attached_clusters( - attached_service.ListAttachedClustersRequest(), - parent='parent_value', - ) - - -def test_list_attached_clusters_rest_pager(transport: str = 'rest'): - client = AttachedClustersClient( - 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 = ( - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - ], - next_page_token='abc', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[], - next_page_token='def', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - ], - next_page_token='ghi', - ), - attached_service.ListAttachedClustersResponse( - attached_clusters=[ - attached_resources.AttachedCluster(), - attached_resources.AttachedCluster(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(attached_service.ListAttachedClustersResponse.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_attached_clusters(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, attached_resources.AttachedCluster) - for i in results) - - pages = list(client.list_attached_clusters(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_attached_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_attached_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_attached_cluster] = mock_rpc - - request = {} - client.delete_attached_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_attached_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_attached_cluster_rest_required_fields(request_type=attached_service.DeleteAttachedClusterRequest): - transport_class = transports.AttachedClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_attached_cluster._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_attached_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "etag", "ignore_errors", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = AttachedClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_attached_cluster(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_attached_cluster_rest_unset_required_fields(): - transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_attached_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "etag", "ignoreErrors", "validateOnly", )) & set(("name", ))) - - -def test_delete_attached_cluster_rest_flattened(): - client = AttachedClustersClient( - 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/attachedClusters/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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_attached_cluster(**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/*/attachedClusters/*}" % client.transport._host, args[1]) - - -def test_delete_attached_cluster_rest_flattened_error(transport: str = 'rest'): - client = AttachedClustersClient( - 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_attached_cluster( - attached_service.DeleteAttachedClusterRequest(), - name='name_value', - ) - - -def test_get_attached_server_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_attached_server_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_attached_server_config] = mock_rpc - - request = {} - client.get_attached_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_attached_server_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_attached_server_config_rest_required_fields(request_type=attached_service.GetAttachedServerConfigRequest): - transport_class = transports.AttachedClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_attached_server_config._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_attached_server_config._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 = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = attached_resources.AttachedServerConfig() - # 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 = attached_resources.AttachedServerConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_attached_server_config(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_attached_server_config_rest_unset_required_fields(): - transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_attached_server_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_attached_server_config_rest_flattened(): - client = AttachedClustersClient( - 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 = attached_resources.AttachedServerConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/attachedServerConfig'} - - # 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 = attached_resources.AttachedServerConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_attached_server_config(**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/*/attachedServerConfig}" % client.transport._host, args[1]) - - -def test_get_attached_server_config_rest_flattened_error(transport: str = 'rest'): - client = AttachedClustersClient( - 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_attached_server_config( - attached_service.GetAttachedServerConfigRequest(), - name='name_value', - ) - - -def test_generate_attached_cluster_install_manifest_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_attached_cluster_install_manifest in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_attached_cluster_install_manifest] = mock_rpc - - request = {} - client.generate_attached_cluster_install_manifest(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_attached_cluster_install_manifest(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_attached_cluster_install_manifest_rest_required_fields(request_type=attached_service.GenerateAttachedClusterInstallManifestRequest): - transport_class = transports.AttachedClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["attached_cluster_id"] = "" - request_init["platform_version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "attachedClusterId" not in jsonified_request - assert "platformVersion" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_attached_cluster_install_manifest._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "attachedClusterId" in jsonified_request - assert jsonified_request["attachedClusterId"] == request_init["attached_cluster_id"] - assert "platformVersion" in jsonified_request - assert jsonified_request["platformVersion"] == request_init["platform_version"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["attachedClusterId"] = 'attached_cluster_id_value' - jsonified_request["platformVersion"] = 'platform_version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_attached_cluster_install_manifest._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("attached_cluster_id", "platform_version", "proxy_config", )) - 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 "attachedClusterId" in jsonified_request - assert jsonified_request["attachedClusterId"] == 'attached_cluster_id_value' - assert "platformVersion" in jsonified_request - assert jsonified_request["platformVersion"] == 'platform_version_value' - - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() - # 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 = attached_service.GenerateAttachedClusterInstallManifestResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.generate_attached_cluster_install_manifest(request) - - expected_params = [ - ( - "attachedClusterId", - "", - ), - ( - "platformVersion", - "", - ), - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_attached_cluster_install_manifest_rest_unset_required_fields(): - transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_attached_cluster_install_manifest._get_unset_required_fields({}) - assert set(unset_fields) == (set(("attachedClusterId", "platformVersion", "proxyConfig", )) & set(("parent", "attachedClusterId", "platformVersion", ))) - - -def test_generate_attached_cluster_install_manifest_rest_flattened(): - client = AttachedClustersClient( - 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 = attached_service.GenerateAttachedClusterInstallManifestResponse() - - # 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', - attached_cluster_id='attached_cluster_id_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 = attached_service.GenerateAttachedClusterInstallManifestResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.generate_attached_cluster_install_manifest(**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/*}:generateAttachedClusterInstallManifest" % client.transport._host, args[1]) - - -def test_generate_attached_cluster_install_manifest_rest_flattened_error(transport: str = 'rest'): - client = AttachedClustersClient( - 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.generate_attached_cluster_install_manifest( - attached_service.GenerateAttachedClusterInstallManifestRequest(), - parent='parent_value', - attached_cluster_id='attached_cluster_id_value', - ) - - -def test_generate_attached_cluster_agent_token_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_attached_cluster_agent_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_attached_cluster_agent_token] = mock_rpc - - request = {} - client.generate_attached_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_attached_cluster_agent_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_attached_cluster_agent_token_rest_required_fields(request_type=attached_service.GenerateAttachedClusterAgentTokenRequest): - transport_class = transports.AttachedClustersRestTransport - - request_init = {} - request_init["attached_cluster"] = "" - request_init["subject_token"] = "" - request_init["subject_token_type"] = "" - request_init["version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_attached_cluster_agent_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["attachedCluster"] = 'attached_cluster_value' - jsonified_request["subjectToken"] = 'subject_token_value' - jsonified_request["subjectTokenType"] = 'subject_token_type_value' - jsonified_request["version"] = 'version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_attached_cluster_agent_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "attachedCluster" in jsonified_request - assert jsonified_request["attachedCluster"] == 'attached_cluster_value' - assert "subjectToken" in jsonified_request - assert jsonified_request["subjectToken"] == 'subject_token_value' - assert "subjectTokenType" in jsonified_request - assert jsonified_request["subjectTokenType"] == 'subject_token_type_value' - assert "version" in jsonified_request - assert jsonified_request["version"] == 'version_value' - - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = attached_service.GenerateAttachedClusterAgentTokenResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = attached_service.GenerateAttachedClusterAgentTokenResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.generate_attached_cluster_agent_token(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_attached_cluster_agent_token_rest_unset_required_fields(): - transport = transports.AttachedClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_attached_cluster_agent_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("attachedCluster", "subjectToken", "subjectTokenType", "version", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AttachedClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AttachedClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AttachedClustersClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AttachedClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AttachedClustersClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AttachedClustersClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AttachedClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AttachedClustersClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AttachedClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AttachedClustersClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AttachedClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AttachedClustersGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AttachedClustersGrpcTransport, - transports.AttachedClustersGrpcAsyncIOTransport, - transports.AttachedClustersRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = AttachedClustersClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_attached_cluster_empty_call_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_attached_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.CreateAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_attached_cluster_empty_call_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_attached_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.UpdateAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_import_attached_cluster_empty_call_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_attached_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.ImportAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_attached_cluster_empty_call_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_cluster), - '__call__') as call: - call.return_value = attached_resources.AttachedCluster() - client.get_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GetAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_attached_clusters_empty_call_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_attached_clusters), - '__call__') as call: - call.return_value = attached_service.ListAttachedClustersResponse() - client.list_attached_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.ListAttachedClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_attached_cluster_empty_call_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_attached_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.DeleteAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_attached_server_config_empty_call_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_server_config), - '__call__') as call: - call.return_value = attached_resources.AttachedServerConfig() - client.get_attached_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GetAttachedServerConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_attached_cluster_install_manifest_empty_call_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_install_manifest), - '__call__') as call: - call.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() - client.generate_attached_cluster_install_manifest(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GenerateAttachedClusterInstallManifestRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_attached_cluster_agent_token_empty_call_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_agent_token), - '__call__') as call: - call.return_value = attached_service.GenerateAttachedClusterAgentTokenResponse() - client.generate_attached_cluster_agent_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GenerateAttachedClusterAgentTokenRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AttachedClustersAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_attached_cluster_empty_call_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.CreateAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_attached_cluster_empty_call_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.UpdateAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_import_attached_cluster_empty_call_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.import_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.ImportAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_attached_cluster_empty_call_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedCluster( - name='name_value', - description='description_value', - platform_version='platform_version_value', - distribution='distribution_value', - cluster_region='cluster_region_value', - state=attached_resources.AttachedCluster.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - kubernetes_version='kubernetes_version_value', - )) - await client.get_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GetAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_attached_clusters_empty_call_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_attached_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.ListAttachedClustersResponse( - next_page_token='next_page_token_value', - )) - await client.list_attached_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.ListAttachedClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_attached_cluster_empty_call_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_attached_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.DeleteAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_attached_server_config_empty_call_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_resources.AttachedServerConfig( - name='name_value', - )) - await client.get_attached_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GetAttachedServerConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_attached_cluster_install_manifest_empty_call_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_install_manifest), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterInstallManifestResponse( - manifest='manifest_value', - )) - await client.generate_attached_cluster_install_manifest(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GenerateAttachedClusterInstallManifestRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_attached_cluster_agent_token_empty_call_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_agent_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attached_service.GenerateAttachedClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - )) - await client.generate_attached_cluster_agent_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GenerateAttachedClusterAgentTokenRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AttachedClustersClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_attached_cluster_rest_bad_request(request_type=attached_service.CreateAttachedClusterRequest): - client = AttachedClustersClient( - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_attached_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - attached_service.CreateAttachedClusterRequest, - dict, -]) -def test_create_attached_cluster_rest_call_success(request_type): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["attached_cluster"] = {'name': 'name_value', 'description': 'description_value', 'oidc_config': {'issuer_url': 'issuer_url_value', 'jwks': b'jwks_blob'}, 'platform_version': 'platform_version_value', 'distribution': 'distribution_value', 'cluster_region': 'cluster_region_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'kubernetes_version': 'kubernetes_version_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}, 'proxy_config': {'kubernetes_secret': {'name': 'name_value', 'namespace': 'namespace_value'}}, 'binary_authorization': {'evaluation_mode': 1}, 'security_posture_config': {'vulnerability_mode': 1}, 'tags': {}} - # 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 = attached_service.CreateAttachedClusterRequest.meta.fields["attached_cluster"] - - 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["attached_cluster"].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["attached_cluster"][field])): - del request_init["attached_cluster"][field][i][subfield] - else: - del request_init["attached_cluster"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_attached_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_attached_cluster_rest_interceptors(null_interceptor): - transport = transports.AttachedClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), - ) - client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_create_attached_cluster") as post, \ - mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_create_attached_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = attached_service.CreateAttachedClusterRequest.pb(attached_service.CreateAttachedClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = attached_service.CreateAttachedClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_attached_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_attached_cluster_rest_bad_request(request_type=attached_service.UpdateAttachedClusterRequest): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'attached_cluster': {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_attached_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - attached_service.UpdateAttachedClusterRequest, - dict, -]) -def test_update_attached_cluster_rest_call_success(request_type): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'attached_cluster': {'name': 'projects/sample1/locations/sample2/attachedClusters/sample3'}} - request_init["attached_cluster"] = {'name': 'projects/sample1/locations/sample2/attachedClusters/sample3', 'description': 'description_value', 'oidc_config': {'issuer_url': 'issuer_url_value', 'jwks': b'jwks_blob'}, 'platform_version': 'platform_version_value', 'distribution': 'distribution_value', 'cluster_region': 'cluster_region_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'kubernetes_version': 'kubernetes_version_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}, 'proxy_config': {'kubernetes_secret': {'name': 'name_value', 'namespace': 'namespace_value'}}, 'binary_authorization': {'evaluation_mode': 1}, 'security_posture_config': {'vulnerability_mode': 1}, 'tags': {}} - # 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 = attached_service.UpdateAttachedClusterRequest.meta.fields["attached_cluster"] - - 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["attached_cluster"].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["attached_cluster"][field])): - del request_init["attached_cluster"][field][i][subfield] - else: - del request_init["attached_cluster"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_attached_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_attached_cluster_rest_interceptors(null_interceptor): - transport = transports.AttachedClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), - ) - client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_update_attached_cluster") as post, \ - mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_update_attached_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = attached_service.UpdateAttachedClusterRequest.pb(attached_service.UpdateAttachedClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = attached_service.UpdateAttachedClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_attached_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_attached_cluster_rest_bad_request(request_type=attached_service.ImportAttachedClusterRequest): - client = AttachedClustersClient( - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.import_attached_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - attached_service.ImportAttachedClusterRequest, - dict, -]) -def test_import_attached_cluster_rest_call_success(request_type): - client = AttachedClustersClient( - 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 = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.import_attached_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_attached_cluster_rest_interceptors(null_interceptor): - transport = transports.AttachedClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), - ) - client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_import_attached_cluster") as post, \ - mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_import_attached_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = attached_service.ImportAttachedClusterRequest.pb(attached_service.ImportAttachedClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = attached_service.ImportAttachedClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_attached_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_attached_cluster_rest_bad_request(request_type=attached_service.GetAttachedClusterRequest): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_attached_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - attached_service.GetAttachedClusterRequest, - dict, -]) -def test_get_attached_cluster_rest_call_success(request_type): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = attached_resources.AttachedCluster( - name='name_value', - description='description_value', - platform_version='platform_version_value', - distribution='distribution_value', - cluster_region='cluster_region_value', - state=attached_resources.AttachedCluster.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - kubernetes_version='kubernetes_version_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = attached_resources.AttachedCluster.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_attached_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_resources.AttachedCluster) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.platform_version == 'platform_version_value' - assert response.distribution == 'distribution_value' - assert response.cluster_region == 'cluster_region_value' - assert response.state == attached_resources.AttachedCluster.State.PROVISIONING - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.kubernetes_version == 'kubernetes_version_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_attached_cluster_rest_interceptors(null_interceptor): - transport = transports.AttachedClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), - ) - client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_get_attached_cluster") as post, \ - mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_get_attached_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = attached_service.GetAttachedClusterRequest.pb(attached_service.GetAttachedClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = attached_resources.AttachedCluster.to_json(attached_resources.AttachedCluster()) - req.return_value.content = return_value - - request = attached_service.GetAttachedClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = attached_resources.AttachedCluster() - - client.get_attached_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_attached_clusters_rest_bad_request(request_type=attached_service.ListAttachedClustersRequest): - client = AttachedClustersClient( - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_attached_clusters(request) - - -@pytest.mark.parametrize("request_type", [ - attached_service.ListAttachedClustersRequest, - dict, -]) -def test_list_attached_clusters_rest_call_success(request_type): - client = AttachedClustersClient( - 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 = attached_service.ListAttachedClustersResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = attached_service.ListAttachedClustersResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_attached_clusters(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttachedClustersPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_attached_clusters_rest_interceptors(null_interceptor): - transport = transports.AttachedClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), - ) - client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_list_attached_clusters") as post, \ - mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_list_attached_clusters") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = attached_service.ListAttachedClustersRequest.pb(attached_service.ListAttachedClustersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = attached_service.ListAttachedClustersResponse.to_json(attached_service.ListAttachedClustersResponse()) - req.return_value.content = return_value - - request = attached_service.ListAttachedClustersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = attached_service.ListAttachedClustersResponse() - - client.list_attached_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_attached_cluster_rest_bad_request(request_type=attached_service.DeleteAttachedClusterRequest): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_attached_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - attached_service.DeleteAttachedClusterRequest, - dict, -]) -def test_delete_attached_cluster_rest_call_success(request_type): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/attachedClusters/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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_attached_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_attached_cluster_rest_interceptors(null_interceptor): - transport = transports.AttachedClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), - ) - client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_delete_attached_cluster") as post, \ - mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_delete_attached_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = attached_service.DeleteAttachedClusterRequest.pb(attached_service.DeleteAttachedClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = attached_service.DeleteAttachedClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_attached_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_attached_server_config_rest_bad_request(request_type=attached_service.GetAttachedServerConfigRequest): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/attachedServerConfig'} - 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_attached_server_config(request) - - -@pytest.mark.parametrize("request_type", [ - attached_service.GetAttachedServerConfigRequest, - dict, -]) -def test_get_attached_server_config_rest_call_success(request_type): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/attachedServerConfig'} - 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 = attached_resources.AttachedServerConfig( - name='name_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = attached_resources.AttachedServerConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_attached_server_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_resources.AttachedServerConfig) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_attached_server_config_rest_interceptors(null_interceptor): - transport = transports.AttachedClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), - ) - client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_get_attached_server_config") as post, \ - mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_get_attached_server_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = attached_service.GetAttachedServerConfigRequest.pb(attached_service.GetAttachedServerConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = attached_resources.AttachedServerConfig.to_json(attached_resources.AttachedServerConfig()) - req.return_value.content = return_value - - request = attached_service.GetAttachedServerConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = attached_resources.AttachedServerConfig() - - client.get_attached_server_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_attached_cluster_install_manifest_rest_bad_request(request_type=attached_service.GenerateAttachedClusterInstallManifestRequest): - client = AttachedClustersClient( - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.generate_attached_cluster_install_manifest(request) - - -@pytest.mark.parametrize("request_type", [ - attached_service.GenerateAttachedClusterInstallManifestRequest, - dict, -]) -def test_generate_attached_cluster_install_manifest_rest_call_success(request_type): - client = AttachedClustersClient( - 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 = attached_service.GenerateAttachedClusterInstallManifestResponse( - manifest='manifest_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = attached_service.GenerateAttachedClusterInstallManifestResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.generate_attached_cluster_install_manifest(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_service.GenerateAttachedClusterInstallManifestResponse) - assert response.manifest == 'manifest_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_attached_cluster_install_manifest_rest_interceptors(null_interceptor): - transport = transports.AttachedClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), - ) - client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_generate_attached_cluster_install_manifest") as post, \ - mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_generate_attached_cluster_install_manifest") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = attached_service.GenerateAttachedClusterInstallManifestRequest.pb(attached_service.GenerateAttachedClusterInstallManifestRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = attached_service.GenerateAttachedClusterInstallManifestResponse.to_json(attached_service.GenerateAttachedClusterInstallManifestResponse()) - req.return_value.content = return_value - - request = attached_service.GenerateAttachedClusterInstallManifestRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = attached_service.GenerateAttachedClusterInstallManifestResponse() - - client.generate_attached_cluster_install_manifest(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_attached_cluster_agent_token_rest_bad_request(request_type=attached_service.GenerateAttachedClusterAgentTokenRequest): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'attached_cluster': 'projects/sample1/locations/sample2/attachedClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.generate_attached_cluster_agent_token(request) - - -@pytest.mark.parametrize("request_type", [ - attached_service.GenerateAttachedClusterAgentTokenRequest, - dict, -]) -def test_generate_attached_cluster_agent_token_rest_call_success(request_type): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'attached_cluster': 'projects/sample1/locations/sample2/attachedClusters/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 = attached_service.GenerateAttachedClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = attached_service.GenerateAttachedClusterAgentTokenResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.generate_attached_cluster_agent_token(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, attached_service.GenerateAttachedClusterAgentTokenResponse) - assert response.access_token == 'access_token_value' - assert response.expires_in == 1078 - assert response.token_type == 'token_type_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_attached_cluster_agent_token_rest_interceptors(null_interceptor): - transport = transports.AttachedClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AttachedClustersRestInterceptor(), - ) - client = AttachedClustersClient(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.AttachedClustersRestInterceptor, "post_generate_attached_cluster_agent_token") as post, \ - mock.patch.object(transports.AttachedClustersRestInterceptor, "pre_generate_attached_cluster_agent_token") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = attached_service.GenerateAttachedClusterAgentTokenRequest.pb(attached_service.GenerateAttachedClusterAgentTokenRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = attached_service.GenerateAttachedClusterAgentTokenResponse.to_json(attached_service.GenerateAttachedClusterAgentTokenResponse()) - req.return_value.content = return_value - - request = attached_service.GenerateAttachedClusterAgentTokenRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = attached_service.GenerateAttachedClusterAgentTokenResponse() - - client.generate_attached_cluster_agent_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = AttachedClustersClient( - 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(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 = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - 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(request_type=operations_pb2.DeleteOperationRequest): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = AttachedClustersClient( - 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(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 = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - 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(request_type=operations_pb2.GetOperationRequest): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = AttachedClustersClient( - 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(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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - 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(request_type=operations_pb2.ListOperationsRequest): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = AttachedClustersClient( - 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(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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_initialize_client_w_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_attached_cluster_empty_call_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_attached_cluster), - '__call__') as call: - client.create_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.CreateAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_attached_cluster_empty_call_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_attached_cluster), - '__call__') as call: - client.update_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.UpdateAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_import_attached_cluster_empty_call_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_attached_cluster), - '__call__') as call: - client.import_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.ImportAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_attached_cluster_empty_call_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_cluster), - '__call__') as call: - client.get_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GetAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_attached_clusters_empty_call_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_attached_clusters), - '__call__') as call: - client.list_attached_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.ListAttachedClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_attached_cluster_empty_call_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_attached_cluster), - '__call__') as call: - client.delete_attached_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.DeleteAttachedClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_attached_server_config_empty_call_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_attached_server_config), - '__call__') as call: - client.get_attached_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GetAttachedServerConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_attached_cluster_install_manifest_empty_call_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_install_manifest), - '__call__') as call: - client.generate_attached_cluster_install_manifest(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GenerateAttachedClusterInstallManifestRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_attached_cluster_agent_token_empty_call_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_attached_cluster_agent_token), - '__call__') as call: - client.generate_attached_cluster_agent_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attached_service.GenerateAttachedClusterAgentTokenRequest() - - assert args[0] == request_msg - - -def test_attached_clusters_rest_lro_client(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have an 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 - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AttachedClustersGrpcTransport, - ) - -def test_attached_clusters_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AttachedClustersTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_attached_clusters_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.gke_multicloud_v1.services.attached_clusters.transports.AttachedClustersTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AttachedClustersTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_attached_cluster', - 'update_attached_cluster', - 'import_attached_cluster', - 'get_attached_cluster', - 'list_attached_clusters', - 'delete_attached_cluster', - 'get_attached_server_config', - 'generate_attached_cluster_install_manifest', - 'generate_attached_cluster_agent_token', - '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_attached_clusters_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.gke_multicloud_v1.services.attached_clusters.transports.AttachedClustersTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AttachedClustersTransport( - 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_attached_clusters_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.gke_multicloud_v1.services.attached_clusters.transports.AttachedClustersTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AttachedClustersTransport() - adc.assert_called_once() - - -def test_attached_clusters_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) - AttachedClustersClient() - 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.AttachedClustersGrpcTransport, - transports.AttachedClustersGrpcAsyncIOTransport, - ], -) -def test_attached_clusters_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.AttachedClustersGrpcTransport, - transports.AttachedClustersGrpcAsyncIOTransport, - transports.AttachedClustersRestTransport, - ], -) -def test_attached_clusters_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.AttachedClustersGrpcTransport, grpc_helpers), - (transports.AttachedClustersGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_attached_clusters_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( - "gkemulticloud.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="gkemulticloud.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AttachedClustersGrpcTransport, transports.AttachedClustersGrpcAsyncIOTransport]) -def test_attached_clusters_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_attached_clusters_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.AttachedClustersRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_attached_clusters_host_no_port(transport_name): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'gkemulticloud.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://gkemulticloud.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_attached_clusters_host_with_port(transport_name): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'gkemulticloud.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://gkemulticloud.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_attached_clusters_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AttachedClustersClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AttachedClustersClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_attached_cluster._session - session2 = client2.transport.create_attached_cluster._session - assert session1 != session2 - session1 = client1.transport.update_attached_cluster._session - session2 = client2.transport.update_attached_cluster._session - assert session1 != session2 - session1 = client1.transport.import_attached_cluster._session - session2 = client2.transport.import_attached_cluster._session - assert session1 != session2 - session1 = client1.transport.get_attached_cluster._session - session2 = client2.transport.get_attached_cluster._session - assert session1 != session2 - session1 = client1.transport.list_attached_clusters._session - session2 = client2.transport.list_attached_clusters._session - assert session1 != session2 - session1 = client1.transport.delete_attached_cluster._session - session2 = client2.transport.delete_attached_cluster._session - assert session1 != session2 - session1 = client1.transport.get_attached_server_config._session - session2 = client2.transport.get_attached_server_config._session - assert session1 != session2 - session1 = client1.transport.generate_attached_cluster_install_manifest._session - session2 = client2.transport.generate_attached_cluster_install_manifest._session - assert session1 != session2 - session1 = client1.transport.generate_attached_cluster_agent_token._session - session2 = client2.transport.generate_attached_cluster_agent_token._session - assert session1 != session2 -def test_attached_clusters_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AttachedClustersGrpcTransport( - 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_attached_clusters_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AttachedClustersGrpcAsyncIOTransport( - 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.AttachedClustersGrpcTransport, transports.AttachedClustersGrpcAsyncIOTransport]) -def test_attached_clusters_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.AttachedClustersGrpcTransport, transports.AttachedClustersGrpcAsyncIOTransport]) -def test_attached_clusters_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_attached_clusters_grpc_lro_client(): - client = AttachedClustersClient( - 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_attached_clusters_grpc_lro_async_client(): - client = AttachedClustersAsyncClient( - 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_attached_cluster_path(): - project = "squid" - location = "clam" - attached_cluster = "whelk" - expected = "projects/{project}/locations/{location}/attachedClusters/{attached_cluster}".format(project=project, location=location, attached_cluster=attached_cluster, ) - actual = AttachedClustersClient.attached_cluster_path(project, location, attached_cluster) - assert expected == actual - - -def test_parse_attached_cluster_path(): - expected = { - "project": "octopus", - "location": "oyster", - "attached_cluster": "nudibranch", - } - path = AttachedClustersClient.attached_cluster_path(**expected) - - # Check that the path construction is reversible. - actual = AttachedClustersClient.parse_attached_cluster_path(path) - assert expected == actual - -def test_attached_server_config_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}/attachedServerConfig".format(project=project, location=location, ) - actual = AttachedClustersClient.attached_server_config_path(project, location) - assert expected == actual - - -def test_parse_attached_server_config_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = AttachedClustersClient.attached_server_config_path(**expected) - - # Check that the path construction is reversible. - actual = AttachedClustersClient.parse_attached_server_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AttachedClustersClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = AttachedClustersClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AttachedClustersClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = AttachedClustersClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = AttachedClustersClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AttachedClustersClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AttachedClustersClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = AttachedClustersClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AttachedClustersClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = AttachedClustersClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = AttachedClustersClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AttachedClustersClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AttachedClustersClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = AttachedClustersClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AttachedClustersClient.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.AttachedClustersTransport, '_prep_wrapped_messages') as prep: - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AttachedClustersTransport, '_prep_wrapped_messages') as prep: - transport_class = AttachedClustersClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_delete_operation(transport: str = "grpc"): - client = AttachedClustersClient( - 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_asyncio"): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AttachedClustersClient( - 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 = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AttachedClustersClient( - 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 = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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 = AttachedClustersClient( - 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_asyncio"): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AttachedClustersClient( - 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 = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AttachedClustersClient( - 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 = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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 = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AttachedClustersClient( - 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 = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AttachedClustersClient( - 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 = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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 = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc_asyncio"): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AttachedClustersClient( - 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 = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AttachedClustersClient( - 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 = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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_transport_close_grpc(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = AttachedClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_rest(): - client = AttachedClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "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 = AttachedClustersClient( - 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", [ - (AttachedClustersClient, transports.AttachedClustersGrpcTransport), - (AttachedClustersAsyncClient, transports.AttachedClustersGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_aws_clusters.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_aws_clusters.py deleted file mode 100644 index bd60753cd32e..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_aws_clusters.py +++ /dev/null @@ -1,13259 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.gke_multicloud_v1.services.aws_clusters import AwsClustersAsyncClient -from google.cloud.gke_multicloud_v1.services.aws_clusters import AwsClustersClient -from google.cloud.gke_multicloud_v1.services.aws_clusters import pagers -from google.cloud.gke_multicloud_v1.services.aws_clusters import transports -from google.cloud.gke_multicloud_v1.types import aws_resources -from google.cloud.gke_multicloud_v1.types import aws_service -from google.cloud.gke_multicloud_v1.types import common_resources -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 - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AwsClustersClient._get_default_mtls_endpoint(None) is None - assert AwsClustersClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AwsClustersClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AwsClustersClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AwsClustersClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AwsClustersClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AwsClustersClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AwsClustersClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AwsClustersClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AwsClustersClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert AwsClustersClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AwsClustersClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AwsClustersClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AwsClustersClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert AwsClustersClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert AwsClustersClient._get_client_cert_source(None, False) is None - assert AwsClustersClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AwsClustersClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert AwsClustersClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AwsClustersClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AwsClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersClient)) -@mock.patch.object(AwsClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AwsClustersClient._DEFAULT_UNIVERSE - default_endpoint = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AwsClustersClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AwsClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AwsClustersClient.DEFAULT_MTLS_ENDPOINT - assert AwsClustersClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AwsClustersClient._get_api_endpoint(None, None, default_universe, "always") == AwsClustersClient.DEFAULT_MTLS_ENDPOINT - assert AwsClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AwsClustersClient.DEFAULT_MTLS_ENDPOINT - assert AwsClustersClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AwsClustersClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AwsClustersClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert AwsClustersClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AwsClustersClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AwsClustersClient._get_universe_domain(None, None) == AwsClustersClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AwsClustersClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AwsClustersClient, "grpc"), - (AwsClustersAsyncClient, "grpc_asyncio"), - (AwsClustersClient, "rest"), -]) -def test_aws_clusters_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 == ( - 'gkemulticloud.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://gkemulticloud.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AwsClustersGrpcTransport, "grpc"), - (transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AwsClustersRestTransport, "rest"), -]) -def test_aws_clusters_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", [ - (AwsClustersClient, "grpc"), - (AwsClustersAsyncClient, "grpc_asyncio"), - (AwsClustersClient, "rest"), -]) -def test_aws_clusters_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 == ( - 'gkemulticloud.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://gkemulticloud.googleapis.com' - ) - - -def test_aws_clusters_client_get_transport_class(): - transport = AwsClustersClient.get_transport_class() - available_transports = [ - transports.AwsClustersGrpcTransport, - transports.AwsClustersRestTransport, - ] - assert transport in available_transports - - transport = AwsClustersClient.get_transport_class("grpc") - assert transport == transports.AwsClustersGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc"), - (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio"), - (AwsClustersClient, transports.AwsClustersRestTransport, "rest"), -]) -@mock.patch.object(AwsClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersClient)) -@mock.patch.object(AwsClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersAsyncClient)) -def test_aws_clusters_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(AwsClustersClient, '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(AwsClustersClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc", "true"), - (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc", "false"), - (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AwsClustersClient, transports.AwsClustersRestTransport, "rest", "true"), - (AwsClustersClient, transports.AwsClustersRestTransport, "rest", "false"), -]) -@mock.patch.object(AwsClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersClient)) -@mock.patch.object(AwsClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_aws_clusters_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - AwsClustersClient, AwsClustersAsyncClient -]) -@mock.patch.object(AwsClustersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AwsClustersClient)) -@mock.patch.object(AwsClustersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AwsClustersAsyncClient)) -def test_aws_clusters_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - AwsClustersClient, AwsClustersAsyncClient -]) -@mock.patch.object(AwsClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersClient)) -@mock.patch.object(AwsClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AwsClustersAsyncClient)) -def test_aws_clusters_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AwsClustersClient._DEFAULT_UNIVERSE - default_endpoint = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AwsClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc"), - (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio"), - (AwsClustersClient, transports.AwsClustersRestTransport, "rest"), -]) -def test_aws_clusters_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc", grpc_helpers), - (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AwsClustersClient, transports.AwsClustersRestTransport, "rest", None), -]) -def test_aws_clusters_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_aws_clusters_client_client_options_from_dict(): - with mock.patch('google.cloud.gke_multicloud_v1.services.aws_clusters.transports.AwsClustersGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AwsClustersClient( - 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", [ - (AwsClustersClient, transports.AwsClustersGrpcTransport, "grpc", grpc_helpers), - (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_aws_clusters_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "gkemulticloud.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="gkemulticloud.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - aws_service.CreateAwsClusterRequest, - dict, -]) -def test_create_aws_cluster(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.CreateAwsClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_aws_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.CreateAwsClusterRequest( - parent='parent_value', - aws_cluster_id='aws_cluster_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_aws_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.CreateAwsClusterRequest( - parent='parent_value', - aws_cluster_id='aws_cluster_id_value', - ) - -def test_create_aws_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_aws_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_aws_cluster] = mock_rpc - request = {} - client.create_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_aws_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_aws_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_aws_cluster] = mock_rpc - - request = {} - await client.create_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_aws_cluster_async(transport: str = 'grpc_asyncio', request_type=aws_service.CreateAwsClusterRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_cluster), - '__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_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.CreateAwsClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_aws_cluster_async_from_dict(): - await test_create_aws_cluster_async(request_type=dict) - -def test_create_aws_cluster_field_headers(): - client = AwsClustersClient( - 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 = aws_service.CreateAwsClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_aws_cluster(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_aws_cluster_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.CreateAwsClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_aws_cluster(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_aws_cluster_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_cluster), - '__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_aws_cluster( - parent='parent_value', - aws_cluster=aws_resources.AwsCluster(name='name_value'), - aws_cluster_id='aws_cluster_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].aws_cluster - mock_val = aws_resources.AwsCluster(name='name_value') - assert arg == mock_val - arg = args[0].aws_cluster_id - mock_val = 'aws_cluster_id_value' - assert arg == mock_val - - -def test_create_aws_cluster_flattened_error(): - client = AwsClustersClient( - 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_aws_cluster( - aws_service.CreateAwsClusterRequest(), - parent='parent_value', - aws_cluster=aws_resources.AwsCluster(name='name_value'), - aws_cluster_id='aws_cluster_id_value', - ) - -@pytest.mark.asyncio -async def test_create_aws_cluster_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_cluster), - '__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_aws_cluster( - parent='parent_value', - aws_cluster=aws_resources.AwsCluster(name='name_value'), - aws_cluster_id='aws_cluster_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].aws_cluster - mock_val = aws_resources.AwsCluster(name='name_value') - assert arg == mock_val - arg = args[0].aws_cluster_id - mock_val = 'aws_cluster_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_aws_cluster_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_aws_cluster( - aws_service.CreateAwsClusterRequest(), - parent='parent_value', - aws_cluster=aws_resources.AwsCluster(name='name_value'), - aws_cluster_id='aws_cluster_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - aws_service.UpdateAwsClusterRequest, - dict, -]) -def test_update_aws_cluster(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.UpdateAwsClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_aws_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.UpdateAwsClusterRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_aws_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.UpdateAwsClusterRequest( - ) - -def test_update_aws_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_aws_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_aws_cluster] = mock_rpc - request = {} - client.update_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_aws_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_aws_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_aws_cluster] = mock_rpc - - request = {} - await client.update_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_aws_cluster_async(transport: str = 'grpc_asyncio', request_type=aws_service.UpdateAwsClusterRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_cluster), - '__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_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.UpdateAwsClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_aws_cluster_async_from_dict(): - await test_update_aws_cluster_async(request_type=dict) - -def test_update_aws_cluster_field_headers(): - client = AwsClustersClient( - 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 = aws_service.UpdateAwsClusterRequest() - - request.aws_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_aws_cluster(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', - 'aws_cluster.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_aws_cluster_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.UpdateAwsClusterRequest() - - request.aws_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_aws_cluster(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', - 'aws_cluster.name=name_value', - ) in kw['metadata'] - - -def test_update_aws_cluster_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_cluster), - '__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_aws_cluster( - aws_cluster=aws_resources.AwsCluster(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].aws_cluster - mock_val = aws_resources.AwsCluster(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_aws_cluster_flattened_error(): - client = AwsClustersClient( - 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_aws_cluster( - aws_service.UpdateAwsClusterRequest(), - aws_cluster=aws_resources.AwsCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_aws_cluster_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_cluster), - '__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_aws_cluster( - aws_cluster=aws_resources.AwsCluster(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].aws_cluster - mock_val = aws_resources.AwsCluster(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_aws_cluster_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_aws_cluster( - aws_service.UpdateAwsClusterRequest(), - aws_cluster=aws_resources.AwsCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GetAwsClusterRequest, - dict, -]) -def test_get_aws_cluster(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsCluster( - name='name_value', - description='description_value', - aws_region='aws_region_value', - state=aws_resources.AwsCluster.State.PROVISIONING, - endpoint='endpoint_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - cluster_ca_certificate='cluster_ca_certificate_value', - ) - response = client.get_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.GetAwsClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsCluster) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.aws_region == 'aws_region_value' - assert response.state == aws_resources.AwsCluster.State.PROVISIONING - assert response.endpoint == 'endpoint_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' - - -def test_get_aws_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.GetAwsClusterRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_aws_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.GetAwsClusterRequest( - name='name_value', - ) - -def test_get_aws_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_aws_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_aws_cluster] = mock_rpc - request = {} - client.get_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_aws_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_aws_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_aws_cluster] = mock_rpc - - request = {} - await client.get_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_aws_cluster_async(transport: str = 'grpc_asyncio', request_type=aws_service.GetAwsClusterRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsCluster( - name='name_value', - description='description_value', - aws_region='aws_region_value', - state=aws_resources.AwsCluster.State.PROVISIONING, - endpoint='endpoint_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - cluster_ca_certificate='cluster_ca_certificate_value', - )) - response = await client.get_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.GetAwsClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsCluster) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.aws_region == 'aws_region_value' - assert response.state == aws_resources.AwsCluster.State.PROVISIONING - assert response.endpoint == 'endpoint_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' - - -@pytest.mark.asyncio -async def test_get_aws_cluster_async_from_dict(): - await test_get_aws_cluster_async(request_type=dict) - -def test_get_aws_cluster_field_headers(): - client = AwsClustersClient( - 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 = aws_service.GetAwsClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_cluster), - '__call__') as call: - call.return_value = aws_resources.AwsCluster() - client.get_aws_cluster(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_aws_cluster_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.GetAwsClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsCluster()) - await client.get_aws_cluster(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_aws_cluster_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsCluster() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_aws_cluster( - 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_aws_cluster_flattened_error(): - client = AwsClustersClient( - 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_aws_cluster( - aws_service.GetAwsClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_aws_cluster_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsCluster() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsCluster()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_aws_cluster( - 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_aws_cluster_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_aws_cluster( - aws_service.GetAwsClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - aws_service.ListAwsClustersRequest, - dict, -]) -def test_list_aws_clusters(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_service.ListAwsClustersResponse( - next_page_token='next_page_token_value', - ) - response = client.list_aws_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.ListAwsClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAwsClustersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_aws_clusters_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.ListAwsClustersRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_clusters), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_aws_clusters(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.ListAwsClustersRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_aws_clusters_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_aws_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_aws_clusters] = mock_rpc - request = {} - client.list_aws_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_aws_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_aws_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_aws_clusters in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_aws_clusters] = mock_rpc - - request = {} - await client.list_aws_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_aws_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_aws_clusters_async(transport: str = 'grpc_asyncio', request_type=aws_service.ListAwsClustersRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsClustersResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_aws_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.ListAwsClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAwsClustersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_aws_clusters_async_from_dict(): - await test_list_aws_clusters_async(request_type=dict) - -def test_list_aws_clusters_field_headers(): - client = AwsClustersClient( - 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 = aws_service.ListAwsClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_clusters), - '__call__') as call: - call.return_value = aws_service.ListAwsClustersResponse() - client.list_aws_clusters(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_aws_clusters_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.ListAwsClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_clusters), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsClustersResponse()) - await client.list_aws_clusters(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_aws_clusters_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_service.ListAwsClustersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_aws_clusters( - 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_aws_clusters_flattened_error(): - client = AwsClustersClient( - 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_aws_clusters( - aws_service.ListAwsClustersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_aws_clusters_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_service.ListAwsClustersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsClustersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_aws_clusters( - 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_aws_clusters_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_aws_clusters( - aws_service.ListAwsClustersRequest(), - parent='parent_value', - ) - - -def test_list_aws_clusters_pager(transport_name: str = "grpc"): - client = AwsClustersClient( - 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_aws_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - ], - next_page_token='abc', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[], - next_page_token='def', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - ], - next_page_token='ghi', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_aws_clusters(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, aws_resources.AwsCluster) - for i in results) -def test_list_aws_clusters_pages(transport_name: str = "grpc"): - client = AwsClustersClient( - 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_aws_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - ], - next_page_token='abc', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[], - next_page_token='def', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - ], - next_page_token='ghi', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - ], - ), - RuntimeError, - ) - pages = list(client.list_aws_clusters(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_aws_clusters_async_pager(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - ], - next_page_token='abc', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[], - next_page_token='def', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - ], - next_page_token='ghi', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_aws_clusters(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, aws_resources.AwsCluster) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_aws_clusters_async_pages(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - ], - next_page_token='abc', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[], - next_page_token='def', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - ], - next_page_token='ghi', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - ], - ), - 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_aws_clusters(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", [ - aws_service.DeleteAwsClusterRequest, - dict, -]) -def test_delete_aws_cluster(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.DeleteAwsClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_aws_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.DeleteAwsClusterRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_aws_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.DeleteAwsClusterRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_aws_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_aws_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_aws_cluster] = mock_rpc - request = {} - client.delete_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_aws_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_aws_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_aws_cluster] = mock_rpc - - request = {} - await client.delete_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_aws_cluster_async(transport: str = 'grpc_asyncio', request_type=aws_service.DeleteAwsClusterRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_cluster), - '__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_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.DeleteAwsClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_aws_cluster_async_from_dict(): - await test_delete_aws_cluster_async(request_type=dict) - -def test_delete_aws_cluster_field_headers(): - client = AwsClustersClient( - 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 = aws_service.DeleteAwsClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_aws_cluster(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_aws_cluster_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.DeleteAwsClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_aws_cluster(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_aws_cluster_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_cluster), - '__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_aws_cluster( - 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_aws_cluster_flattened_error(): - client = AwsClustersClient( - 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_aws_cluster( - aws_service.DeleteAwsClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_aws_cluster_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_cluster), - '__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_aws_cluster( - 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_aws_cluster_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_aws_cluster( - aws_service.DeleteAwsClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GenerateAwsClusterAgentTokenRequest, - dict, -]) -def test_generate_aws_cluster_agent_token(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_cluster_agent_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_service.GenerateAwsClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - ) - response = client.generate_aws_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.GenerateAwsClusterAgentTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_service.GenerateAwsClusterAgentTokenResponse) - assert response.access_token == 'access_token_value' - assert response.expires_in == 1078 - assert response.token_type == 'token_type_value' - - -def test_generate_aws_cluster_agent_token_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.GenerateAwsClusterAgentTokenRequest( - aws_cluster='aws_cluster_value', - subject_token='subject_token_value', - subject_token_type='subject_token_type_value', - version='version_value', - node_pool_id='node_pool_id_value', - grant_type='grant_type_value', - audience='audience_value', - scope='scope_value', - requested_token_type='requested_token_type_value', - options='options_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_cluster_agent_token), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_aws_cluster_agent_token(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.GenerateAwsClusterAgentTokenRequest( - aws_cluster='aws_cluster_value', - subject_token='subject_token_value', - subject_token_type='subject_token_type_value', - version='version_value', - node_pool_id='node_pool_id_value', - grant_type='grant_type_value', - audience='audience_value', - scope='scope_value', - requested_token_type='requested_token_type_value', - options='options_value', - ) - -def test_generate_aws_cluster_agent_token_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_aws_cluster_agent_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_aws_cluster_agent_token] = mock_rpc - request = {} - client.generate_aws_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_aws_cluster_agent_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_aws_cluster_agent_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_aws_cluster_agent_token in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_aws_cluster_agent_token] = mock_rpc - - request = {} - await client.generate_aws_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_aws_cluster_agent_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_aws_cluster_agent_token_async(transport: str = 'grpc_asyncio', request_type=aws_service.GenerateAwsClusterAgentTokenRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_cluster_agent_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - )) - response = await client.generate_aws_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.GenerateAwsClusterAgentTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_service.GenerateAwsClusterAgentTokenResponse) - assert response.access_token == 'access_token_value' - assert response.expires_in == 1078 - assert response.token_type == 'token_type_value' - - -@pytest.mark.asyncio -async def test_generate_aws_cluster_agent_token_async_from_dict(): - await test_generate_aws_cluster_agent_token_async(request_type=dict) - -def test_generate_aws_cluster_agent_token_field_headers(): - client = AwsClustersClient( - 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 = aws_service.GenerateAwsClusterAgentTokenRequest() - - request.aws_cluster = 'aws_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_cluster_agent_token), - '__call__') as call: - call.return_value = aws_service.GenerateAwsClusterAgentTokenResponse() - client.generate_aws_cluster_agent_token(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', - 'aws_cluster=aws_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_aws_cluster_agent_token_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.GenerateAwsClusterAgentTokenRequest() - - request.aws_cluster = 'aws_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_cluster_agent_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsClusterAgentTokenResponse()) - await client.generate_aws_cluster_agent_token(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', - 'aws_cluster=aws_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - aws_service.GenerateAwsAccessTokenRequest, - dict, -]) -def test_generate_aws_access_token(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_service.GenerateAwsAccessTokenResponse( - access_token='access_token_value', - ) - response = client.generate_aws_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.GenerateAwsAccessTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_service.GenerateAwsAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -def test_generate_aws_access_token_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.GenerateAwsAccessTokenRequest( - aws_cluster='aws_cluster_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_access_token), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_aws_access_token(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.GenerateAwsAccessTokenRequest( - aws_cluster='aws_cluster_value', - ) - -def test_generate_aws_access_token_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_aws_access_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_aws_access_token] = mock_rpc - request = {} - client.generate_aws_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_aws_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_aws_access_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_aws_access_token in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_aws_access_token] = mock_rpc - - request = {} - await client.generate_aws_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_aws_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_aws_access_token_async(transport: str = 'grpc_asyncio', request_type=aws_service.GenerateAwsAccessTokenRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsAccessTokenResponse( - access_token='access_token_value', - )) - response = await client.generate_aws_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.GenerateAwsAccessTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_service.GenerateAwsAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.asyncio -async def test_generate_aws_access_token_async_from_dict(): - await test_generate_aws_access_token_async(request_type=dict) - -def test_generate_aws_access_token_field_headers(): - client = AwsClustersClient( - 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 = aws_service.GenerateAwsAccessTokenRequest() - - request.aws_cluster = 'aws_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_access_token), - '__call__') as call: - call.return_value = aws_service.GenerateAwsAccessTokenResponse() - client.generate_aws_access_token(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', - 'aws_cluster=aws_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_aws_access_token_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.GenerateAwsAccessTokenRequest() - - request.aws_cluster = 'aws_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_access_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsAccessTokenResponse()) - await client.generate_aws_access_token(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', - 'aws_cluster=aws_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - aws_service.CreateAwsNodePoolRequest, - dict, -]) -def test_create_aws_node_pool(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.CreateAwsNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_aws_node_pool_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.CreateAwsNodePoolRequest( - parent='parent_value', - aws_node_pool_id='aws_node_pool_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_aws_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.CreateAwsNodePoolRequest( - parent='parent_value', - aws_node_pool_id='aws_node_pool_id_value', - ) - -def test_create_aws_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_aws_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_aws_node_pool] = mock_rpc - request = {} - client.create_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_aws_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_aws_node_pool in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_aws_node_pool] = mock_rpc - - request = {} - await client.create_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_aws_node_pool_async(transport: str = 'grpc_asyncio', request_type=aws_service.CreateAwsNodePoolRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_node_pool), - '__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_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.CreateAwsNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_aws_node_pool_async_from_dict(): - await test_create_aws_node_pool_async(request_type=dict) - -def test_create_aws_node_pool_field_headers(): - client = AwsClustersClient( - 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 = aws_service.CreateAwsNodePoolRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_aws_node_pool(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_aws_node_pool_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.CreateAwsNodePoolRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_aws_node_pool(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_aws_node_pool_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_node_pool), - '__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_aws_node_pool( - parent='parent_value', - aws_node_pool=aws_resources.AwsNodePool(name='name_value'), - aws_node_pool_id='aws_node_pool_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].aws_node_pool - mock_val = aws_resources.AwsNodePool(name='name_value') - assert arg == mock_val - arg = args[0].aws_node_pool_id - mock_val = 'aws_node_pool_id_value' - assert arg == mock_val - - -def test_create_aws_node_pool_flattened_error(): - client = AwsClustersClient( - 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_aws_node_pool( - aws_service.CreateAwsNodePoolRequest(), - parent='parent_value', - aws_node_pool=aws_resources.AwsNodePool(name='name_value'), - aws_node_pool_id='aws_node_pool_id_value', - ) - -@pytest.mark.asyncio -async def test_create_aws_node_pool_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_node_pool), - '__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_aws_node_pool( - parent='parent_value', - aws_node_pool=aws_resources.AwsNodePool(name='name_value'), - aws_node_pool_id='aws_node_pool_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].aws_node_pool - mock_val = aws_resources.AwsNodePool(name='name_value') - assert arg == mock_val - arg = args[0].aws_node_pool_id - mock_val = 'aws_node_pool_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_aws_node_pool_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_aws_node_pool( - aws_service.CreateAwsNodePoolRequest(), - parent='parent_value', - aws_node_pool=aws_resources.AwsNodePool(name='name_value'), - aws_node_pool_id='aws_node_pool_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - aws_service.UpdateAwsNodePoolRequest, - dict, -]) -def test_update_aws_node_pool(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.UpdateAwsNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_aws_node_pool_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.UpdateAwsNodePoolRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_aws_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.UpdateAwsNodePoolRequest( - ) - -def test_update_aws_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_aws_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_aws_node_pool] = mock_rpc - request = {} - client.update_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_aws_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_aws_node_pool in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_aws_node_pool] = mock_rpc - - request = {} - await client.update_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_aws_node_pool_async(transport: str = 'grpc_asyncio', request_type=aws_service.UpdateAwsNodePoolRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_node_pool), - '__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_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.UpdateAwsNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_aws_node_pool_async_from_dict(): - await test_update_aws_node_pool_async(request_type=dict) - -def test_update_aws_node_pool_field_headers(): - client = AwsClustersClient( - 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 = aws_service.UpdateAwsNodePoolRequest() - - request.aws_node_pool.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_aws_node_pool(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', - 'aws_node_pool.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_aws_node_pool_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.UpdateAwsNodePoolRequest() - - request.aws_node_pool.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_aws_node_pool(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', - 'aws_node_pool.name=name_value', - ) in kw['metadata'] - - -def test_update_aws_node_pool_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_node_pool), - '__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_aws_node_pool( - aws_node_pool=aws_resources.AwsNodePool(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].aws_node_pool - mock_val = aws_resources.AwsNodePool(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_aws_node_pool_flattened_error(): - client = AwsClustersClient( - 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_aws_node_pool( - aws_service.UpdateAwsNodePoolRequest(), - aws_node_pool=aws_resources.AwsNodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_aws_node_pool_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_node_pool), - '__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_aws_node_pool( - aws_node_pool=aws_resources.AwsNodePool(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].aws_node_pool - mock_val = aws_resources.AwsNodePool(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_aws_node_pool_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_aws_node_pool( - aws_service.UpdateAwsNodePoolRequest(), - aws_node_pool=aws_resources.AwsNodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - aws_service.RollbackAwsNodePoolUpdateRequest, - dict, -]) -def test_rollback_aws_node_pool_update(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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.rollback_aws_node_pool_update), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.rollback_aws_node_pool_update(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.RollbackAwsNodePoolUpdateRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_rollback_aws_node_pool_update_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.RollbackAwsNodePoolUpdateRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_aws_node_pool_update), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.rollback_aws_node_pool_update(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.RollbackAwsNodePoolUpdateRequest( - name='name_value', - ) - -def test_rollback_aws_node_pool_update_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.rollback_aws_node_pool_update in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.rollback_aws_node_pool_update] = mock_rpc - request = {} - client.rollback_aws_node_pool_update(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.rollback_aws_node_pool_update(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_rollback_aws_node_pool_update_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.rollback_aws_node_pool_update in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.rollback_aws_node_pool_update] = mock_rpc - - request = {} - await client.rollback_aws_node_pool_update(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.rollback_aws_node_pool_update(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_rollback_aws_node_pool_update_async(transport: str = 'grpc_asyncio', request_type=aws_service.RollbackAwsNodePoolUpdateRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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.rollback_aws_node_pool_update), - '__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.rollback_aws_node_pool_update(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.RollbackAwsNodePoolUpdateRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_rollback_aws_node_pool_update_async_from_dict(): - await test_rollback_aws_node_pool_update_async(request_type=dict) - -def test_rollback_aws_node_pool_update_field_headers(): - client = AwsClustersClient( - 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 = aws_service.RollbackAwsNodePoolUpdateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_aws_node_pool_update), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rollback_aws_node_pool_update(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_rollback_aws_node_pool_update_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.RollbackAwsNodePoolUpdateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_aws_node_pool_update), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.rollback_aws_node_pool_update(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_rollback_aws_node_pool_update_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_aws_node_pool_update), - '__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.rollback_aws_node_pool_update( - 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_rollback_aws_node_pool_update_flattened_error(): - client = AwsClustersClient( - 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.rollback_aws_node_pool_update( - aws_service.RollbackAwsNodePoolUpdateRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_rollback_aws_node_pool_update_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_aws_node_pool_update), - '__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.rollback_aws_node_pool_update( - 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_rollback_aws_node_pool_update_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.rollback_aws_node_pool_update( - aws_service.RollbackAwsNodePoolUpdateRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GetAwsNodePoolRequest, - dict, -]) -def test_get_aws_node_pool(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsNodePool( - name='name_value', - version='version_value', - subnet_id='subnet_id_value', - state=aws_resources.AwsNodePool.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - ) - response = client.get_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.GetAwsNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsNodePool) - assert response.name == 'name_value' - assert response.version == 'version_value' - assert response.subnet_id == 'subnet_id_value' - assert response.state == aws_resources.AwsNodePool.State.PROVISIONING - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - - -def test_get_aws_node_pool_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.GetAwsNodePoolRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_aws_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.GetAwsNodePoolRequest( - name='name_value', - ) - -def test_get_aws_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_aws_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_aws_node_pool] = mock_rpc - request = {} - client.get_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_aws_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_aws_node_pool in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_aws_node_pool] = mock_rpc - - request = {} - await client.get_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_aws_node_pool_async(transport: str = 'grpc_asyncio', request_type=aws_service.GetAwsNodePoolRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsNodePool( - name='name_value', - version='version_value', - subnet_id='subnet_id_value', - state=aws_resources.AwsNodePool.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - )) - response = await client.get_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.GetAwsNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsNodePool) - assert response.name == 'name_value' - assert response.version == 'version_value' - assert response.subnet_id == 'subnet_id_value' - assert response.state == aws_resources.AwsNodePool.State.PROVISIONING - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_aws_node_pool_async_from_dict(): - await test_get_aws_node_pool_async(request_type=dict) - -def test_get_aws_node_pool_field_headers(): - client = AwsClustersClient( - 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 = aws_service.GetAwsNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_node_pool), - '__call__') as call: - call.return_value = aws_resources.AwsNodePool() - client.get_aws_node_pool(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_aws_node_pool_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.GetAwsNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsNodePool()) - await client.get_aws_node_pool(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_aws_node_pool_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsNodePool() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_aws_node_pool( - 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_aws_node_pool_flattened_error(): - client = AwsClustersClient( - 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_aws_node_pool( - aws_service.GetAwsNodePoolRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_aws_node_pool_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsNodePool() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsNodePool()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_aws_node_pool( - 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_aws_node_pool_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_aws_node_pool( - aws_service.GetAwsNodePoolRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - aws_service.ListAwsNodePoolsRequest, - dict, -]) -def test_list_aws_node_pools(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_service.ListAwsNodePoolsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_aws_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.ListAwsNodePoolsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAwsNodePoolsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_aws_node_pools_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.ListAwsNodePoolsRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_node_pools), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_aws_node_pools(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.ListAwsNodePoolsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_aws_node_pools_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_aws_node_pools in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_aws_node_pools] = mock_rpc - request = {} - client.list_aws_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_aws_node_pools(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_aws_node_pools_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_aws_node_pools in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_aws_node_pools] = mock_rpc - - request = {} - await client.list_aws_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_aws_node_pools(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_aws_node_pools_async(transport: str = 'grpc_asyncio', request_type=aws_service.ListAwsNodePoolsRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsNodePoolsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_aws_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.ListAwsNodePoolsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAwsNodePoolsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_aws_node_pools_async_from_dict(): - await test_list_aws_node_pools_async(request_type=dict) - -def test_list_aws_node_pools_field_headers(): - client = AwsClustersClient( - 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 = aws_service.ListAwsNodePoolsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_node_pools), - '__call__') as call: - call.return_value = aws_service.ListAwsNodePoolsResponse() - client.list_aws_node_pools(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_aws_node_pools_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.ListAwsNodePoolsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_node_pools), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsNodePoolsResponse()) - await client.list_aws_node_pools(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_aws_node_pools_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_service.ListAwsNodePoolsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_aws_node_pools( - 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_aws_node_pools_flattened_error(): - client = AwsClustersClient( - 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_aws_node_pools( - aws_service.ListAwsNodePoolsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_aws_node_pools_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_service.ListAwsNodePoolsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsNodePoolsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_aws_node_pools( - 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_aws_node_pools_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_aws_node_pools( - aws_service.ListAwsNodePoolsRequest(), - parent='parent_value', - ) - - -def test_list_aws_node_pools_pager(transport_name: str = "grpc"): - client = AwsClustersClient( - 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_aws_node_pools), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - ], - next_page_token='abc', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[], - next_page_token='def', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - ], - next_page_token='ghi', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_aws_node_pools(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, aws_resources.AwsNodePool) - for i in results) -def test_list_aws_node_pools_pages(transport_name: str = "grpc"): - client = AwsClustersClient( - 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_aws_node_pools), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - ], - next_page_token='abc', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[], - next_page_token='def', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - ], - next_page_token='ghi', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - ], - ), - RuntimeError, - ) - pages = list(client.list_aws_node_pools(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_aws_node_pools_async_pager(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_node_pools), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - ], - next_page_token='abc', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[], - next_page_token='def', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - ], - next_page_token='ghi', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_aws_node_pools(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, aws_resources.AwsNodePool) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_aws_node_pools_async_pages(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_node_pools), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - ], - next_page_token='abc', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[], - next_page_token='def', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - ], - next_page_token='ghi', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - ], - ), - 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_aws_node_pools(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", [ - aws_service.DeleteAwsNodePoolRequest, - dict, -]) -def test_delete_aws_node_pool(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.DeleteAwsNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_aws_node_pool_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.DeleteAwsNodePoolRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_aws_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.DeleteAwsNodePoolRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_aws_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_aws_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_aws_node_pool] = mock_rpc - request = {} - client.delete_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_aws_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_aws_node_pool in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_aws_node_pool] = mock_rpc - - request = {} - await client.delete_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_aws_node_pool_async(transport: str = 'grpc_asyncio', request_type=aws_service.DeleteAwsNodePoolRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_node_pool), - '__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_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.DeleteAwsNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_aws_node_pool_async_from_dict(): - await test_delete_aws_node_pool_async(request_type=dict) - -def test_delete_aws_node_pool_field_headers(): - client = AwsClustersClient( - 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 = aws_service.DeleteAwsNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_aws_node_pool(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_aws_node_pool_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.DeleteAwsNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_aws_node_pool(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_aws_node_pool_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_node_pool), - '__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_aws_node_pool( - 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_aws_node_pool_flattened_error(): - client = AwsClustersClient( - 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_aws_node_pool( - aws_service.DeleteAwsNodePoolRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_aws_node_pool_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_node_pool), - '__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_aws_node_pool( - 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_aws_node_pool_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_aws_node_pool( - aws_service.DeleteAwsNodePoolRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GetAwsOpenIdConfigRequest, - dict, -]) -def test_get_aws_open_id_config(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_open_id_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsOpenIdConfig( - issuer='issuer_value', - jwks_uri='jwks_uri_value', - response_types_supported=['response_types_supported_value'], - subject_types_supported=['subject_types_supported_value'], - id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], - claims_supported=['claims_supported_value'], - grant_types=['grant_types_value'], - ) - response = client.get_aws_open_id_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.GetAwsOpenIdConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsOpenIdConfig) - assert response.issuer == 'issuer_value' - assert response.jwks_uri == 'jwks_uri_value' - assert response.response_types_supported == ['response_types_supported_value'] - assert response.subject_types_supported == ['subject_types_supported_value'] - assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] - assert response.claims_supported == ['claims_supported_value'] - assert response.grant_types == ['grant_types_value'] - - -def test_get_aws_open_id_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.GetAwsOpenIdConfigRequest( - aws_cluster='aws_cluster_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_open_id_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_aws_open_id_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.GetAwsOpenIdConfigRequest( - aws_cluster='aws_cluster_value', - ) - -def test_get_aws_open_id_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_aws_open_id_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_aws_open_id_config] = mock_rpc - request = {} - client.get_aws_open_id_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_aws_open_id_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_aws_open_id_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_aws_open_id_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_aws_open_id_config] = mock_rpc - - request = {} - await client.get_aws_open_id_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_aws_open_id_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_aws_open_id_config_async(transport: str = 'grpc_asyncio', request_type=aws_service.GetAwsOpenIdConfigRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_open_id_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsOpenIdConfig( - issuer='issuer_value', - jwks_uri='jwks_uri_value', - response_types_supported=['response_types_supported_value'], - subject_types_supported=['subject_types_supported_value'], - id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], - claims_supported=['claims_supported_value'], - grant_types=['grant_types_value'], - )) - response = await client.get_aws_open_id_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.GetAwsOpenIdConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsOpenIdConfig) - assert response.issuer == 'issuer_value' - assert response.jwks_uri == 'jwks_uri_value' - assert response.response_types_supported == ['response_types_supported_value'] - assert response.subject_types_supported == ['subject_types_supported_value'] - assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] - assert response.claims_supported == ['claims_supported_value'] - assert response.grant_types == ['grant_types_value'] - - -@pytest.mark.asyncio -async def test_get_aws_open_id_config_async_from_dict(): - await test_get_aws_open_id_config_async(request_type=dict) - -def test_get_aws_open_id_config_field_headers(): - client = AwsClustersClient( - 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 = aws_service.GetAwsOpenIdConfigRequest() - - request.aws_cluster = 'aws_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_open_id_config), - '__call__') as call: - call.return_value = aws_resources.AwsOpenIdConfig() - client.get_aws_open_id_config(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', - 'aws_cluster=aws_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_aws_open_id_config_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.GetAwsOpenIdConfigRequest() - - request.aws_cluster = 'aws_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_open_id_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsOpenIdConfig()) - await client.get_aws_open_id_config(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', - 'aws_cluster=aws_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - aws_service.GetAwsJsonWebKeysRequest, - dict, -]) -def test_get_aws_json_web_keys(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_json_web_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsJsonWebKeys( - ) - response = client.get_aws_json_web_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.GetAwsJsonWebKeysRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsJsonWebKeys) - - -def test_get_aws_json_web_keys_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.GetAwsJsonWebKeysRequest( - aws_cluster='aws_cluster_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_json_web_keys), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_aws_json_web_keys(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.GetAwsJsonWebKeysRequest( - aws_cluster='aws_cluster_value', - ) - -def test_get_aws_json_web_keys_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_aws_json_web_keys in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_aws_json_web_keys] = mock_rpc - request = {} - client.get_aws_json_web_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_aws_json_web_keys(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_aws_json_web_keys_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_aws_json_web_keys in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_aws_json_web_keys] = mock_rpc - - request = {} - await client.get_aws_json_web_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_aws_json_web_keys(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_aws_json_web_keys_async(transport: str = 'grpc_asyncio', request_type=aws_service.GetAwsJsonWebKeysRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_json_web_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsJsonWebKeys( - )) - response = await client.get_aws_json_web_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.GetAwsJsonWebKeysRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsJsonWebKeys) - - -@pytest.mark.asyncio -async def test_get_aws_json_web_keys_async_from_dict(): - await test_get_aws_json_web_keys_async(request_type=dict) - -def test_get_aws_json_web_keys_field_headers(): - client = AwsClustersClient( - 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 = aws_service.GetAwsJsonWebKeysRequest() - - request.aws_cluster = 'aws_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_json_web_keys), - '__call__') as call: - call.return_value = aws_resources.AwsJsonWebKeys() - client.get_aws_json_web_keys(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', - 'aws_cluster=aws_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_aws_json_web_keys_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.GetAwsJsonWebKeysRequest() - - request.aws_cluster = 'aws_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_json_web_keys), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsJsonWebKeys()) - await client.get_aws_json_web_keys(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', - 'aws_cluster=aws_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - aws_service.GetAwsServerConfigRequest, - dict, -]) -def test_get_aws_server_config(request_type, transport: str = 'grpc'): - client = AwsClustersClient( - 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_aws_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsServerConfig( - name='name_value', - supported_aws_regions=['supported_aws_regions_value'], - ) - response = client.get_aws_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = aws_service.GetAwsServerConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsServerConfig) - assert response.name == 'name_value' - assert response.supported_aws_regions == ['supported_aws_regions_value'] - - -def test_get_aws_server_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = aws_service.GetAwsServerConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_server_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_aws_server_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == aws_service.GetAwsServerConfigRequest( - name='name_value', - ) - -def test_get_aws_server_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_aws_server_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_aws_server_config] = mock_rpc - request = {} - client.get_aws_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_aws_server_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_aws_server_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_aws_server_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_aws_server_config] = mock_rpc - - request = {} - await client.get_aws_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_aws_server_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_aws_server_config_async(transport: str = 'grpc_asyncio', request_type=aws_service.GetAwsServerConfigRequest): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_aws_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsServerConfig( - name='name_value', - supported_aws_regions=['supported_aws_regions_value'], - )) - response = await client.get_aws_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = aws_service.GetAwsServerConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsServerConfig) - assert response.name == 'name_value' - assert response.supported_aws_regions == ['supported_aws_regions_value'] - - -@pytest.mark.asyncio -async def test_get_aws_server_config_async_from_dict(): - await test_get_aws_server_config_async(request_type=dict) - -def test_get_aws_server_config_field_headers(): - client = AwsClustersClient( - 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 = aws_service.GetAwsServerConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_server_config), - '__call__') as call: - call.return_value = aws_resources.AwsServerConfig() - client.get_aws_server_config(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_aws_server_config_field_headers_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = aws_service.GetAwsServerConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_server_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsServerConfig()) - await client.get_aws_server_config(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_aws_server_config_flattened(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsServerConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_aws_server_config( - 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_aws_server_config_flattened_error(): - client = AwsClustersClient( - 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_aws_server_config( - aws_service.GetAwsServerConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_aws_server_config_flattened_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = aws_resources.AwsServerConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsServerConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_aws_server_config( - 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_aws_server_config_flattened_error_async(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_aws_server_config( - aws_service.GetAwsServerConfigRequest(), - name='name_value', - ) - - -def test_create_aws_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_aws_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_aws_cluster] = mock_rpc - - request = {} - client.create_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_aws_cluster_rest_required_fields(request_type=aws_service.CreateAwsClusterRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["aws_cluster_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "awsClusterId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_aws_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "awsClusterId" in jsonified_request - assert jsonified_request["awsClusterId"] == request_init["aws_cluster_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["awsClusterId"] = 'aws_cluster_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_aws_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("aws_cluster_id", "validate_only", )) - 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 "awsClusterId" in jsonified_request - assert jsonified_request["awsClusterId"] == 'aws_cluster_id_value' - - client = AwsClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_aws_cluster(request) - - expected_params = [ - ( - "awsClusterId", - "", - ), - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_aws_cluster_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_aws_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("awsClusterId", "validateOnly", )) & set(("parent", "awsCluster", "awsClusterId", ))) - - -def test_create_aws_cluster_rest_flattened(): - client = AwsClustersClient( - 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', - aws_cluster=aws_resources.AwsCluster(name='name_value'), - aws_cluster_id='aws_cluster_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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_aws_cluster(**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/*}/awsClusters" % client.transport._host, args[1]) - - -def test_create_aws_cluster_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_cluster( - aws_service.CreateAwsClusterRequest(), - parent='parent_value', - aws_cluster=aws_resources.AwsCluster(name='name_value'), - aws_cluster_id='aws_cluster_id_value', - ) - - -def test_update_aws_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_aws_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_aws_cluster] = mock_rpc - - request = {} - client.update_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_aws_cluster_rest_required_fields(request_type=aws_service.UpdateAwsClusterRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_aws_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_aws_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AwsClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_aws_cluster(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_aws_cluster_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_aws_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("awsCluster", "updateMask", ))) - - -def test_update_aws_cluster_rest_flattened(): - client = AwsClustersClient( - 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 = {'aws_cluster': {'name': 'projects/sample1/locations/sample2/awsClusters/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - aws_cluster=aws_resources.AwsCluster(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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_aws_cluster(**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/{aws_cluster.name=projects/*/locations/*/awsClusters/*}" % client.transport._host, args[1]) - - -def test_update_aws_cluster_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_cluster( - aws_service.UpdateAwsClusterRequest(), - aws_cluster=aws_resources.AwsCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_aws_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_aws_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_aws_cluster] = mock_rpc - - request = {} - client.get_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_aws_cluster_rest_required_fields(request_type=aws_service.GetAwsClusterRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_cluster._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_aws_cluster._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 = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = aws_resources.AwsCluster() - # 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 = aws_resources.AwsCluster.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_aws_cluster(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_aws_cluster_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_aws_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_aws_cluster_rest_flattened(): - client = AwsClustersClient( - 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 = aws_resources.AwsCluster() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/awsClusters/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 = aws_resources.AwsCluster.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_aws_cluster(**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/*/awsClusters/*}" % client.transport._host, args[1]) - - -def test_get_aws_cluster_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_cluster( - aws_service.GetAwsClusterRequest(), - name='name_value', - ) - - -def test_list_aws_clusters_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_aws_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_aws_clusters] = mock_rpc - - request = {} - client.list_aws_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_aws_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_aws_clusters_rest_required_fields(request_type=aws_service.ListAwsClustersRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_aws_clusters._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_aws_clusters._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - 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 = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = aws_service.ListAwsClustersResponse() - # 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 = aws_service.ListAwsClustersResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_aws_clusters(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_aws_clusters_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_aws_clusters._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_aws_clusters_rest_flattened(): - client = AwsClustersClient( - 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 = aws_service.ListAwsClustersResponse() - - # 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 = aws_service.ListAwsClustersResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_aws_clusters(**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/*}/awsClusters" % client.transport._host, args[1]) - - -def test_list_aws_clusters_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_clusters( - aws_service.ListAwsClustersRequest(), - parent='parent_value', - ) - - -def test_list_aws_clusters_rest_pager(transport: str = 'rest'): - client = AwsClustersClient( - 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 = ( - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - ], - next_page_token='abc', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[], - next_page_token='def', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - ], - next_page_token='ghi', - ), - aws_service.ListAwsClustersResponse( - aws_clusters=[ - aws_resources.AwsCluster(), - aws_resources.AwsCluster(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(aws_service.ListAwsClustersResponse.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_aws_clusters(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, aws_resources.AwsCluster) - for i in results) - - pages = list(client.list_aws_clusters(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_aws_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_aws_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_aws_cluster] = mock_rpc - - request = {} - client.delete_aws_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_aws_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_aws_cluster_rest_required_fields(request_type=aws_service.DeleteAwsClusterRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_aws_cluster._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_aws_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "etag", "ignore_errors", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = AwsClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_aws_cluster(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_aws_cluster_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_aws_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "etag", "ignoreErrors", "validateOnly", )) & set(("name", ))) - - -def test_delete_aws_cluster_rest_flattened(): - client = AwsClustersClient( - 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/awsClusters/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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_aws_cluster(**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/*/awsClusters/*}" % client.transport._host, args[1]) - - -def test_delete_aws_cluster_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_cluster( - aws_service.DeleteAwsClusterRequest(), - name='name_value', - ) - - -def test_generate_aws_cluster_agent_token_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_aws_cluster_agent_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_aws_cluster_agent_token] = mock_rpc - - request = {} - client.generate_aws_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_aws_cluster_agent_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_aws_cluster_agent_token_rest_required_fields(request_type=aws_service.GenerateAwsClusterAgentTokenRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["aws_cluster"] = "" - request_init["subject_token"] = "" - request_init["subject_token_type"] = "" - request_init["version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_aws_cluster_agent_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["awsCluster"] = 'aws_cluster_value' - jsonified_request["subjectToken"] = 'subject_token_value' - jsonified_request["subjectTokenType"] = 'subject_token_type_value' - jsonified_request["version"] = 'version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_aws_cluster_agent_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "awsCluster" in jsonified_request - assert jsonified_request["awsCluster"] == 'aws_cluster_value' - assert "subjectToken" in jsonified_request - assert jsonified_request["subjectToken"] == 'subject_token_value' - assert "subjectTokenType" in jsonified_request - assert jsonified_request["subjectTokenType"] == 'subject_token_type_value' - assert "version" in jsonified_request - assert jsonified_request["version"] == 'version_value' - - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = aws_service.GenerateAwsClusterAgentTokenResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = aws_service.GenerateAwsClusterAgentTokenResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.generate_aws_cluster_agent_token(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_aws_cluster_agent_token_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_aws_cluster_agent_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("awsCluster", "subjectToken", "subjectTokenType", "version", ))) - - -def test_generate_aws_access_token_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_aws_access_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_aws_access_token] = mock_rpc - - request = {} - client.generate_aws_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_aws_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_aws_access_token_rest_required_fields(request_type=aws_service.GenerateAwsAccessTokenRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["aws_cluster"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_aws_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["awsCluster"] = 'aws_cluster_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_aws_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "awsCluster" in jsonified_request - assert jsonified_request["awsCluster"] == 'aws_cluster_value' - - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = aws_service.GenerateAwsAccessTokenResponse() - # 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 = aws_service.GenerateAwsAccessTokenResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.generate_aws_access_token(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_aws_access_token_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_aws_access_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("awsCluster", ))) - - -def test_create_aws_node_pool_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_aws_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_aws_node_pool] = mock_rpc - - request = {} - client.create_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_aws_node_pool_rest_required_fields(request_type=aws_service.CreateAwsNodePoolRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["aws_node_pool_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "awsNodePoolId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_aws_node_pool._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "awsNodePoolId" in jsonified_request - assert jsonified_request["awsNodePoolId"] == request_init["aws_node_pool_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["awsNodePoolId"] = 'aws_node_pool_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_aws_node_pool._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("aws_node_pool_id", "validate_only", )) - 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 "awsNodePoolId" in jsonified_request - assert jsonified_request["awsNodePoolId"] == 'aws_node_pool_id_value' - - client = AwsClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_aws_node_pool(request) - - expected_params = [ - ( - "awsNodePoolId", - "", - ), - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_aws_node_pool_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_aws_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(("awsNodePoolId", "validateOnly", )) & set(("parent", "awsNodePool", "awsNodePoolId", ))) - - -def test_create_aws_node_pool_rest_flattened(): - client = AwsClustersClient( - 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/awsClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - aws_node_pool=aws_resources.AwsNodePool(name='name_value'), - aws_node_pool_id='aws_node_pool_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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_aws_node_pool(**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/*/awsClusters/*}/awsNodePools" % client.transport._host, args[1]) - - -def test_create_aws_node_pool_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_node_pool( - aws_service.CreateAwsNodePoolRequest(), - parent='parent_value', - aws_node_pool=aws_resources.AwsNodePool(name='name_value'), - aws_node_pool_id='aws_node_pool_id_value', - ) - - -def test_update_aws_node_pool_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_aws_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_aws_node_pool] = mock_rpc - - request = {} - client.update_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_aws_node_pool_rest_required_fields(request_type=aws_service.UpdateAwsNodePoolRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_aws_node_pool._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_aws_node_pool._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AwsClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_aws_node_pool(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_aws_node_pool_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_aws_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("awsNodePool", "updateMask", ))) - - -def test_update_aws_node_pool_rest_flattened(): - client = AwsClustersClient( - 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 = {'aws_node_pool': {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - aws_node_pool=aws_resources.AwsNodePool(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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_aws_node_pool(**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/{aws_node_pool.name=projects/*/locations/*/awsClusters/*/awsNodePools/*}" % client.transport._host, args[1]) - - -def test_update_aws_node_pool_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_node_pool( - aws_service.UpdateAwsNodePoolRequest(), - aws_node_pool=aws_resources.AwsNodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_rollback_aws_node_pool_update_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.rollback_aws_node_pool_update in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.rollback_aws_node_pool_update] = mock_rpc - - request = {} - client.rollback_aws_node_pool_update(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.rollback_aws_node_pool_update(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_rollback_aws_node_pool_update_rest_required_fields(request_type=aws_service.RollbackAwsNodePoolUpdateRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_aws_node_pool_update._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()).rollback_aws_node_pool_update._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 = AwsClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.rollback_aws_node_pool_update(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_rollback_aws_node_pool_update_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.rollback_aws_node_pool_update._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_rollback_aws_node_pool_update_rest_flattened(): - client = AwsClustersClient( - 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/awsClusters/sample3/awsNodePools/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.rollback_aws_node_pool_update(**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/*/awsClusters/*/awsNodePools/*}:rollback" % client.transport._host, args[1]) - - -def test_rollback_aws_node_pool_update_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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.rollback_aws_node_pool_update( - aws_service.RollbackAwsNodePoolUpdateRequest(), - name='name_value', - ) - - -def test_get_aws_node_pool_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_aws_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_aws_node_pool] = mock_rpc - - request = {} - client.get_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_aws_node_pool_rest_required_fields(request_type=aws_service.GetAwsNodePoolRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_node_pool._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_aws_node_pool._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 = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = aws_resources.AwsNodePool() - # 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 = aws_resources.AwsNodePool.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_aws_node_pool(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_aws_node_pool_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_aws_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_aws_node_pool_rest_flattened(): - client = AwsClustersClient( - 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 = aws_resources.AwsNodePool() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = aws_resources.AwsNodePool.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_aws_node_pool(**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/*/awsClusters/*/awsNodePools/*}" % client.transport._host, args[1]) - - -def test_get_aws_node_pool_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_node_pool( - aws_service.GetAwsNodePoolRequest(), - name='name_value', - ) - - -def test_list_aws_node_pools_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_aws_node_pools in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_aws_node_pools] = mock_rpc - - request = {} - client.list_aws_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_aws_node_pools(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_aws_node_pools_rest_required_fields(request_type=aws_service.ListAwsNodePoolsRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_aws_node_pools._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_aws_node_pools._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - 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 = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = aws_service.ListAwsNodePoolsResponse() - # 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 = aws_service.ListAwsNodePoolsResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_aws_node_pools(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_aws_node_pools_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_aws_node_pools._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_aws_node_pools_rest_flattened(): - client = AwsClustersClient( - 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 = aws_service.ListAwsNodePoolsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/awsClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = aws_service.ListAwsNodePoolsResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_aws_node_pools(**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/*/awsClusters/*}/awsNodePools" % client.transport._host, args[1]) - - -def test_list_aws_node_pools_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_node_pools( - aws_service.ListAwsNodePoolsRequest(), - parent='parent_value', - ) - - -def test_list_aws_node_pools_rest_pager(transport: str = 'rest'): - client = AwsClustersClient( - 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 = ( - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - ], - next_page_token='abc', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[], - next_page_token='def', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - ], - next_page_token='ghi', - ), - aws_service.ListAwsNodePoolsResponse( - aws_node_pools=[ - aws_resources.AwsNodePool(), - aws_resources.AwsNodePool(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(aws_service.ListAwsNodePoolsResponse.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/awsClusters/sample3'} - - pager = client.list_aws_node_pools(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, aws_resources.AwsNodePool) - for i in results) - - pages = list(client.list_aws_node_pools(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_aws_node_pool_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_aws_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_aws_node_pool] = mock_rpc - - request = {} - client.delete_aws_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_aws_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_aws_node_pool_rest_required_fields(request_type=aws_service.DeleteAwsNodePoolRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_aws_node_pool._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_aws_node_pool._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "etag", "ignore_errors", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = AwsClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_aws_node_pool(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_aws_node_pool_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_aws_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "etag", "ignoreErrors", "validateOnly", )) & set(("name", ))) - - -def test_delete_aws_node_pool_rest_flattened(): - client = AwsClustersClient( - 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/awsClusters/sample3/awsNodePools/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_aws_node_pool(**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/*/awsClusters/*/awsNodePools/*}" % client.transport._host, args[1]) - - -def test_delete_aws_node_pool_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_node_pool( - aws_service.DeleteAwsNodePoolRequest(), - name='name_value', - ) - - -def test_get_aws_open_id_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_aws_open_id_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_aws_open_id_config] = mock_rpc - - request = {} - client.get_aws_open_id_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_aws_open_id_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_aws_open_id_config_rest_required_fields(request_type=aws_service.GetAwsOpenIdConfigRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["aws_cluster"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_open_id_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["awsCluster"] = 'aws_cluster_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_open_id_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "awsCluster" in jsonified_request - assert jsonified_request["awsCluster"] == 'aws_cluster_value' - - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = aws_resources.AwsOpenIdConfig() - # 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 = aws_resources.AwsOpenIdConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_aws_open_id_config(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_aws_open_id_config_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_aws_open_id_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("awsCluster", ))) - - -def test_get_aws_json_web_keys_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_aws_json_web_keys in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_aws_json_web_keys] = mock_rpc - - request = {} - client.get_aws_json_web_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_aws_json_web_keys(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_aws_json_web_keys_rest_required_fields(request_type=aws_service.GetAwsJsonWebKeysRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["aws_cluster"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_json_web_keys._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["awsCluster"] = 'aws_cluster_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_json_web_keys._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "awsCluster" in jsonified_request - assert jsonified_request["awsCluster"] == 'aws_cluster_value' - - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = aws_resources.AwsJsonWebKeys() - # 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 = aws_resources.AwsJsonWebKeys.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_aws_json_web_keys(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_aws_json_web_keys_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_aws_json_web_keys._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("awsCluster", ))) - - -def test_get_aws_server_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_aws_server_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_aws_server_config] = mock_rpc - - request = {} - client.get_aws_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_aws_server_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_aws_server_config_rest_required_fields(request_type=aws_service.GetAwsServerConfigRequest): - transport_class = transports.AwsClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_aws_server_config._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_aws_server_config._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 = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = aws_resources.AwsServerConfig() - # 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 = aws_resources.AwsServerConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_aws_server_config(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_aws_server_config_rest_unset_required_fields(): - transport = transports.AwsClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_aws_server_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_aws_server_config_rest_flattened(): - client = AwsClustersClient( - 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 = aws_resources.AwsServerConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/awsServerConfig'} - - # 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 = aws_resources.AwsServerConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_aws_server_config(**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/*/awsServerConfig}" % client.transport._host, args[1]) - - -def test_get_aws_server_config_rest_flattened_error(transport: str = 'rest'): - client = AwsClustersClient( - 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_aws_server_config( - aws_service.GetAwsServerConfigRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AwsClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AwsClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AwsClustersClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AwsClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AwsClustersClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AwsClustersClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AwsClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AwsClustersClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AwsClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AwsClustersClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AwsClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AwsClustersGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AwsClustersGrpcTransport, - transports.AwsClustersGrpcAsyncIOTransport, - transports.AwsClustersRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = AwsClustersClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_aws_cluster_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.CreateAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_aws_cluster_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.UpdateAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_aws_cluster_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_cluster), - '__call__') as call: - call.return_value = aws_resources.AwsCluster() - client.get_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_aws_clusters_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_clusters), - '__call__') as call: - call.return_value = aws_service.ListAwsClustersResponse() - client.list_aws_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.ListAwsClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_aws_cluster_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.DeleteAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_aws_cluster_agent_token_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_cluster_agent_token), - '__call__') as call: - call.return_value = aws_service.GenerateAwsClusterAgentTokenResponse() - client.generate_aws_cluster_agent_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GenerateAwsClusterAgentTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_aws_access_token_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_access_token), - '__call__') as call: - call.return_value = aws_service.GenerateAwsAccessTokenResponse() - client.generate_aws_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GenerateAwsAccessTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_aws_node_pool_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.CreateAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_aws_node_pool_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.UpdateAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_rollback_aws_node_pool_update_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.rollback_aws_node_pool_update), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.rollback_aws_node_pool_update(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.RollbackAwsNodePoolUpdateRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_aws_node_pool_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_node_pool), - '__call__') as call: - call.return_value = aws_resources.AwsNodePool() - client.get_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_aws_node_pools_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_node_pools), - '__call__') as call: - call.return_value = aws_service.ListAwsNodePoolsResponse() - client.list_aws_node_pools(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.ListAwsNodePoolsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_aws_node_pool_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.DeleteAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_aws_open_id_config_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_open_id_config), - '__call__') as call: - call.return_value = aws_resources.AwsOpenIdConfig() - client.get_aws_open_id_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsOpenIdConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_aws_json_web_keys_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_json_web_keys), - '__call__') as call: - call.return_value = aws_resources.AwsJsonWebKeys() - client.get_aws_json_web_keys(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsJsonWebKeysRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_aws_server_config_empty_call_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_server_config), - '__call__') as call: - call.return_value = aws_resources.AwsServerConfig() - client.get_aws_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsServerConfigRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AwsClustersAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_aws_cluster_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.CreateAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_aws_cluster_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.UpdateAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_aws_cluster_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsCluster( - name='name_value', - description='description_value', - aws_region='aws_region_value', - state=aws_resources.AwsCluster.State.PROVISIONING, - endpoint='endpoint_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - cluster_ca_certificate='cluster_ca_certificate_value', - )) - await client.get_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_aws_clusters_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsClustersResponse( - next_page_token='next_page_token_value', - )) - await client.list_aws_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.ListAwsClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_aws_cluster_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.DeleteAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_aws_cluster_agent_token_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_cluster_agent_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - )) - await client.generate_aws_cluster_agent_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GenerateAwsClusterAgentTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_aws_access_token_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.GenerateAwsAccessTokenResponse( - access_token='access_token_value', - )) - await client.generate_aws_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GenerateAwsAccessTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_aws_node_pool_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.CreateAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_aws_node_pool_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.UpdateAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_rollback_aws_node_pool_update_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.rollback_aws_node_pool_update), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.rollback_aws_node_pool_update(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.RollbackAwsNodePoolUpdateRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_aws_node_pool_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsNodePool( - name='name_value', - version='version_value', - subnet_id='subnet_id_value', - state=aws_resources.AwsNodePool.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - )) - await client.get_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_aws_node_pools_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_service.ListAwsNodePoolsResponse( - next_page_token='next_page_token_value', - )) - await client.list_aws_node_pools(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.ListAwsNodePoolsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_aws_node_pool_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.DeleteAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_aws_open_id_config_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_open_id_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsOpenIdConfig( - issuer='issuer_value', - jwks_uri='jwks_uri_value', - response_types_supported=['response_types_supported_value'], - subject_types_supported=['subject_types_supported_value'], - id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], - claims_supported=['claims_supported_value'], - grant_types=['grant_types_value'], - )) - await client.get_aws_open_id_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsOpenIdConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_aws_json_web_keys_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_json_web_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsJsonWebKeys( - )) - await client.get_aws_json_web_keys(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsJsonWebKeysRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_aws_server_config_empty_call_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(aws_resources.AwsServerConfig( - name='name_value', - supported_aws_regions=['supported_aws_regions_value'], - )) - await client.get_aws_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsServerConfigRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AwsClustersClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_aws_cluster_rest_bad_request(request_type=aws_service.CreateAwsClusterRequest): - client = AwsClustersClient( - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_aws_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.CreateAwsClusterRequest, - dict, -]) -def test_create_aws_cluster_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["aws_cluster"] = {'name': 'name_value', 'description': 'description_value', 'networking': {'vpc_id': 'vpc_id_value', 'pod_address_cidr_blocks': ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'], 'service_address_cidr_blocks': ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'], 'per_node_pool_sg_rules_disabled': True}, 'aws_region': 'aws_region_value', 'control_plane': {'version': 'version_value', 'instance_type': 'instance_type_value', 'ssh_config': {'ec2_key_pair': 'ec2_key_pair_value'}, 'subnet_ids': ['subnet_ids_value1', 'subnet_ids_value2'], 'security_group_ids': ['security_group_ids_value1', 'security_group_ids_value2'], 'iam_instance_profile': 'iam_instance_profile_value', 'root_volume': {'size_gib': 844, 'volume_type': 1, 'iops': 443, 'throughput': 1114, 'kms_key_arn': 'kms_key_arn_value'}, 'main_volume': {}, 'database_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'tags': {}, 'aws_services_authentication': {'role_arn': 'role_arn_value', 'role_session_name': 'role_session_name_value'}, 'proxy_config': {'secret_arn': 'secret_arn_value', 'secret_version': 'secret_version_value'}, 'config_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'instance_placement': {'tenancy': 1}}, 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'state': 1, 'endpoint': 'endpoint_value', 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'cluster_ca_certificate': 'cluster_ca_certificate_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}, 'binary_authorization': {'evaluation_mode': 1}} - # 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 = aws_service.CreateAwsClusterRequest.meta.fields["aws_cluster"] - - 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["aws_cluster"].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["aws_cluster"][field])): - del request_init["aws_cluster"][field][i][subfield] - else: - del request_init["aws_cluster"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_aws_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_aws_cluster_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_create_aws_cluster") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_create_aws_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.CreateAwsClusterRequest.pb(aws_service.CreateAwsClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = aws_service.CreateAwsClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_aws_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_aws_cluster_rest_bad_request(request_type=aws_service.UpdateAwsClusterRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'aws_cluster': {'name': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_aws_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.UpdateAwsClusterRequest, - dict, -]) -def test_update_aws_cluster_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'aws_cluster': {'name': 'projects/sample1/locations/sample2/awsClusters/sample3'}} - request_init["aws_cluster"] = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3', 'description': 'description_value', 'networking': {'vpc_id': 'vpc_id_value', 'pod_address_cidr_blocks': ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'], 'service_address_cidr_blocks': ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'], 'per_node_pool_sg_rules_disabled': True}, 'aws_region': 'aws_region_value', 'control_plane': {'version': 'version_value', 'instance_type': 'instance_type_value', 'ssh_config': {'ec2_key_pair': 'ec2_key_pair_value'}, 'subnet_ids': ['subnet_ids_value1', 'subnet_ids_value2'], 'security_group_ids': ['security_group_ids_value1', 'security_group_ids_value2'], 'iam_instance_profile': 'iam_instance_profile_value', 'root_volume': {'size_gib': 844, 'volume_type': 1, 'iops': 443, 'throughput': 1114, 'kms_key_arn': 'kms_key_arn_value'}, 'main_volume': {}, 'database_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'tags': {}, 'aws_services_authentication': {'role_arn': 'role_arn_value', 'role_session_name': 'role_session_name_value'}, 'proxy_config': {'secret_arn': 'secret_arn_value', 'secret_version': 'secret_version_value'}, 'config_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'instance_placement': {'tenancy': 1}}, 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'state': 1, 'endpoint': 'endpoint_value', 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'cluster_ca_certificate': 'cluster_ca_certificate_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}, 'binary_authorization': {'evaluation_mode': 1}} - # 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 = aws_service.UpdateAwsClusterRequest.meta.fields["aws_cluster"] - - 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["aws_cluster"].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["aws_cluster"][field])): - del request_init["aws_cluster"][field][i][subfield] - else: - del request_init["aws_cluster"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_aws_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_aws_cluster_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_update_aws_cluster") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_update_aws_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.UpdateAwsClusterRequest.pb(aws_service.UpdateAwsClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = aws_service.UpdateAwsClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_aws_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_aws_cluster_rest_bad_request(request_type=aws_service.GetAwsClusterRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_aws_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GetAwsClusterRequest, - dict, -]) -def test_get_aws_cluster_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/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 = aws_resources.AwsCluster( - name='name_value', - description='description_value', - aws_region='aws_region_value', - state=aws_resources.AwsCluster.State.PROVISIONING, - endpoint='endpoint_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - cluster_ca_certificate='cluster_ca_certificate_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = aws_resources.AwsCluster.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_aws_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsCluster) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.aws_region == 'aws_region_value' - assert response.state == aws_resources.AwsCluster.State.PROVISIONING - assert response.endpoint == 'endpoint_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_aws_cluster_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_get_aws_cluster") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_get_aws_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.GetAwsClusterRequest.pb(aws_service.GetAwsClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = aws_resources.AwsCluster.to_json(aws_resources.AwsCluster()) - req.return_value.content = return_value - - request = aws_service.GetAwsClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = aws_resources.AwsCluster() - - client.get_aws_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_aws_clusters_rest_bad_request(request_type=aws_service.ListAwsClustersRequest): - client = AwsClustersClient( - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_aws_clusters(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.ListAwsClustersRequest, - dict, -]) -def test_list_aws_clusters_rest_call_success(request_type): - client = AwsClustersClient( - 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 = aws_service.ListAwsClustersResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = aws_service.ListAwsClustersResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_aws_clusters(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAwsClustersPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_aws_clusters_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_list_aws_clusters") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_list_aws_clusters") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.ListAwsClustersRequest.pb(aws_service.ListAwsClustersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = aws_service.ListAwsClustersResponse.to_json(aws_service.ListAwsClustersResponse()) - req.return_value.content = return_value - - request = aws_service.ListAwsClustersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = aws_service.ListAwsClustersResponse() - - client.list_aws_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_aws_cluster_rest_bad_request(request_type=aws_service.DeleteAwsClusterRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_aws_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.DeleteAwsClusterRequest, - dict, -]) -def test_delete_aws_cluster_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_aws_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_aws_cluster_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_delete_aws_cluster") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_delete_aws_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.DeleteAwsClusterRequest.pb(aws_service.DeleteAwsClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = aws_service.DeleteAwsClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_aws_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_aws_cluster_agent_token_rest_bad_request(request_type=aws_service.GenerateAwsClusterAgentTokenRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.generate_aws_cluster_agent_token(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GenerateAwsClusterAgentTokenRequest, - dict, -]) -def test_generate_aws_cluster_agent_token_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = aws_service.GenerateAwsClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = aws_service.GenerateAwsClusterAgentTokenResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.generate_aws_cluster_agent_token(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_service.GenerateAwsClusterAgentTokenResponse) - assert response.access_token == 'access_token_value' - assert response.expires_in == 1078 - assert response.token_type == 'token_type_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_aws_cluster_agent_token_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_generate_aws_cluster_agent_token") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_generate_aws_cluster_agent_token") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.GenerateAwsClusterAgentTokenRequest.pb(aws_service.GenerateAwsClusterAgentTokenRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = aws_service.GenerateAwsClusterAgentTokenResponse.to_json(aws_service.GenerateAwsClusterAgentTokenResponse()) - req.return_value.content = return_value - - request = aws_service.GenerateAwsClusterAgentTokenRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = aws_service.GenerateAwsClusterAgentTokenResponse() - - client.generate_aws_cluster_agent_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_aws_access_token_rest_bad_request(request_type=aws_service.GenerateAwsAccessTokenRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.generate_aws_access_token(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GenerateAwsAccessTokenRequest, - dict, -]) -def test_generate_aws_access_token_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = aws_service.GenerateAwsAccessTokenResponse( - access_token='access_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = aws_service.GenerateAwsAccessTokenResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.generate_aws_access_token(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_service.GenerateAwsAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_aws_access_token_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_generate_aws_access_token") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_generate_aws_access_token") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.GenerateAwsAccessTokenRequest.pb(aws_service.GenerateAwsAccessTokenRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = aws_service.GenerateAwsAccessTokenResponse.to_json(aws_service.GenerateAwsAccessTokenResponse()) - req.return_value.content = return_value - - request = aws_service.GenerateAwsAccessTokenRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = aws_service.GenerateAwsAccessTokenResponse() - - client.generate_aws_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_aws_node_pool_rest_bad_request(request_type=aws_service.CreateAwsNodePoolRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_aws_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.CreateAwsNodePoolRequest, - dict, -]) -def test_create_aws_node_pool_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/awsClusters/sample3'} - request_init["aws_node_pool"] = {'name': 'name_value', 'version': 'version_value', 'config': {'instance_type': 'instance_type_value', 'root_volume': {'size_gib': 844, 'volume_type': 1, 'iops': 443, 'throughput': 1114, 'kms_key_arn': 'kms_key_arn_value'}, 'taints': [{'key': 'key_value', 'value': 'value_value', 'effect': 1}], 'labels': {}, 'tags': {}, 'iam_instance_profile': 'iam_instance_profile_value', 'image_type': 'image_type_value', 'ssh_config': {'ec2_key_pair': 'ec2_key_pair_value'}, 'security_group_ids': ['security_group_ids_value1', 'security_group_ids_value2'], 'proxy_config': {'secret_arn': 'secret_arn_value', 'secret_version': 'secret_version_value'}, 'config_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'instance_placement': {'tenancy': 1}, 'autoscaling_metrics_collection': {'granularity': 'granularity_value', 'metrics': ['metrics_value1', 'metrics_value2']}, 'spot_config': {'instance_types': ['instance_types_value1', 'instance_types_value2']}}, 'autoscaling': {'min_node_count': 1489, 'max_node_count': 1491}, 'subnet_id': 'subnet_id_value', 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'max_pods_constraint': {'max_pods_per_node': 1798}, 'errors': [{'message': 'message_value'}], 'management': {'auto_repair': True}, 'kubelet_config': {'insecure_kubelet_readonly_port_enabled': True, 'cpu_manager_policy': 'cpu_manager_policy_value', 'cpu_cfs_quota': True, 'cpu_cfs_quota_period': 'cpu_cfs_quota_period_value', 'pod_pids_limit': 1488}, 'update_settings': {'surge_settings': {'max_surge': 971, 'max_unavailable': 1577}}} - # 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 = aws_service.CreateAwsNodePoolRequest.meta.fields["aws_node_pool"] - - 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["aws_node_pool"].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["aws_node_pool"][field])): - del request_init["aws_node_pool"][field][i][subfield] - else: - del request_init["aws_node_pool"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_aws_node_pool(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_aws_node_pool_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_create_aws_node_pool") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_create_aws_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.CreateAwsNodePoolRequest.pb(aws_service.CreateAwsNodePoolRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = aws_service.CreateAwsNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_aws_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_aws_node_pool_rest_bad_request(request_type=aws_service.UpdateAwsNodePoolRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'aws_node_pool': {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_aws_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.UpdateAwsNodePoolRequest, - dict, -]) -def test_update_aws_node_pool_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'aws_node_pool': {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'}} - request_init["aws_node_pool"] = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4', 'version': 'version_value', 'config': {'instance_type': 'instance_type_value', 'root_volume': {'size_gib': 844, 'volume_type': 1, 'iops': 443, 'throughput': 1114, 'kms_key_arn': 'kms_key_arn_value'}, 'taints': [{'key': 'key_value', 'value': 'value_value', 'effect': 1}], 'labels': {}, 'tags': {}, 'iam_instance_profile': 'iam_instance_profile_value', 'image_type': 'image_type_value', 'ssh_config': {'ec2_key_pair': 'ec2_key_pair_value'}, 'security_group_ids': ['security_group_ids_value1', 'security_group_ids_value2'], 'proxy_config': {'secret_arn': 'secret_arn_value', 'secret_version': 'secret_version_value'}, 'config_encryption': {'kms_key_arn': 'kms_key_arn_value'}, 'instance_placement': {'tenancy': 1}, 'autoscaling_metrics_collection': {'granularity': 'granularity_value', 'metrics': ['metrics_value1', 'metrics_value2']}, 'spot_config': {'instance_types': ['instance_types_value1', 'instance_types_value2']}}, 'autoscaling': {'min_node_count': 1489, 'max_node_count': 1491}, 'subnet_id': 'subnet_id_value', 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'max_pods_constraint': {'max_pods_per_node': 1798}, 'errors': [{'message': 'message_value'}], 'management': {'auto_repair': True}, 'kubelet_config': {'insecure_kubelet_readonly_port_enabled': True, 'cpu_manager_policy': 'cpu_manager_policy_value', 'cpu_cfs_quota': True, 'cpu_cfs_quota_period': 'cpu_cfs_quota_period_value', 'pod_pids_limit': 1488}, 'update_settings': {'surge_settings': {'max_surge': 971, 'max_unavailable': 1577}}} - # 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 = aws_service.UpdateAwsNodePoolRequest.meta.fields["aws_node_pool"] - - 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["aws_node_pool"].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["aws_node_pool"][field])): - del request_init["aws_node_pool"][field][i][subfield] - else: - del request_init["aws_node_pool"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_aws_node_pool(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_aws_node_pool_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_update_aws_node_pool") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_update_aws_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.UpdateAwsNodePoolRequest.pb(aws_service.UpdateAwsNodePoolRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = aws_service.UpdateAwsNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_aws_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_rollback_aws_node_pool_update_rest_bad_request(request_type=aws_service.RollbackAwsNodePoolUpdateRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.rollback_aws_node_pool_update(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.RollbackAwsNodePoolUpdateRequest, - dict, -]) -def test_rollback_aws_node_pool_update_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.rollback_aws_node_pool_update(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_rollback_aws_node_pool_update_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_rollback_aws_node_pool_update") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_rollback_aws_node_pool_update") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.RollbackAwsNodePoolUpdateRequest.pb(aws_service.RollbackAwsNodePoolUpdateRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = aws_service.RollbackAwsNodePoolUpdateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.rollback_aws_node_pool_update(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_aws_node_pool_rest_bad_request(request_type=aws_service.GetAwsNodePoolRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_aws_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GetAwsNodePoolRequest, - dict, -]) -def test_get_aws_node_pool_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = aws_resources.AwsNodePool( - name='name_value', - version='version_value', - subnet_id='subnet_id_value', - state=aws_resources.AwsNodePool.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = aws_resources.AwsNodePool.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_aws_node_pool(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsNodePool) - assert response.name == 'name_value' - assert response.version == 'version_value' - assert response.subnet_id == 'subnet_id_value' - assert response.state == aws_resources.AwsNodePool.State.PROVISIONING - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_aws_node_pool_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_get_aws_node_pool") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_get_aws_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.GetAwsNodePoolRequest.pb(aws_service.GetAwsNodePoolRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = aws_resources.AwsNodePool.to_json(aws_resources.AwsNodePool()) - req.return_value.content = return_value - - request = aws_service.GetAwsNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = aws_resources.AwsNodePool() - - client.get_aws_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_aws_node_pools_rest_bad_request(request_type=aws_service.ListAwsNodePoolsRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_aws_node_pools(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.ListAwsNodePoolsRequest, - dict, -]) -def test_list_aws_node_pools_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/awsClusters/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 = aws_service.ListAwsNodePoolsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = aws_service.ListAwsNodePoolsResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_aws_node_pools(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAwsNodePoolsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_aws_node_pools_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_list_aws_node_pools") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_list_aws_node_pools") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.ListAwsNodePoolsRequest.pb(aws_service.ListAwsNodePoolsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = aws_service.ListAwsNodePoolsResponse.to_json(aws_service.ListAwsNodePoolsResponse()) - req.return_value.content = return_value - - request = aws_service.ListAwsNodePoolsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = aws_service.ListAwsNodePoolsResponse() - - client.list_aws_node_pools(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_aws_node_pool_rest_bad_request(request_type=aws_service.DeleteAwsNodePoolRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_aws_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.DeleteAwsNodePoolRequest, - dict, -]) -def test_delete_aws_node_pool_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsClusters/sample3/awsNodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_aws_node_pool(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_aws_node_pool_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_delete_aws_node_pool") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_delete_aws_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.DeleteAwsNodePoolRequest.pb(aws_service.DeleteAwsNodePoolRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = aws_service.DeleteAwsNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_aws_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_aws_open_id_config_rest_bad_request(request_type=aws_service.GetAwsOpenIdConfigRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_aws_open_id_config(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GetAwsOpenIdConfigRequest, - dict, -]) -def test_get_aws_open_id_config_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = aws_resources.AwsOpenIdConfig( - issuer='issuer_value', - jwks_uri='jwks_uri_value', - response_types_supported=['response_types_supported_value'], - subject_types_supported=['subject_types_supported_value'], - id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], - claims_supported=['claims_supported_value'], - grant_types=['grant_types_value'], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = aws_resources.AwsOpenIdConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_aws_open_id_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsOpenIdConfig) - assert response.issuer == 'issuer_value' - assert response.jwks_uri == 'jwks_uri_value' - assert response.response_types_supported == ['response_types_supported_value'] - assert response.subject_types_supported == ['subject_types_supported_value'] - assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] - assert response.claims_supported == ['claims_supported_value'] - assert response.grant_types == ['grant_types_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_aws_open_id_config_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_get_aws_open_id_config") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_get_aws_open_id_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.GetAwsOpenIdConfigRequest.pb(aws_service.GetAwsOpenIdConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = aws_resources.AwsOpenIdConfig.to_json(aws_resources.AwsOpenIdConfig()) - req.return_value.content = return_value - - request = aws_service.GetAwsOpenIdConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = aws_resources.AwsOpenIdConfig() - - client.get_aws_open_id_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_aws_json_web_keys_rest_bad_request(request_type=aws_service.GetAwsJsonWebKeysRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_aws_json_web_keys(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GetAwsJsonWebKeysRequest, - dict, -]) -def test_get_aws_json_web_keys_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'aws_cluster': 'projects/sample1/locations/sample2/awsClusters/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 = aws_resources.AwsJsonWebKeys( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = aws_resources.AwsJsonWebKeys.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_aws_json_web_keys(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsJsonWebKeys) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_aws_json_web_keys_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_get_aws_json_web_keys") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_get_aws_json_web_keys") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.GetAwsJsonWebKeysRequest.pb(aws_service.GetAwsJsonWebKeysRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = aws_resources.AwsJsonWebKeys.to_json(aws_resources.AwsJsonWebKeys()) - req.return_value.content = return_value - - request = aws_service.GetAwsJsonWebKeysRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = aws_resources.AwsJsonWebKeys() - - client.get_aws_json_web_keys(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_aws_server_config_rest_bad_request(request_type=aws_service.GetAwsServerConfigRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsServerConfig'} - 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_aws_server_config(request) - - -@pytest.mark.parametrize("request_type", [ - aws_service.GetAwsServerConfigRequest, - dict, -]) -def test_get_aws_server_config_rest_call_success(request_type): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/awsServerConfig'} - 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 = aws_resources.AwsServerConfig( - name='name_value', - supported_aws_regions=['supported_aws_regions_value'], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = aws_resources.AwsServerConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_aws_server_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, aws_resources.AwsServerConfig) - assert response.name == 'name_value' - assert response.supported_aws_regions == ['supported_aws_regions_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_aws_server_config_rest_interceptors(null_interceptor): - transport = transports.AwsClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AwsClustersRestInterceptor(), - ) - client = AwsClustersClient(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.AwsClustersRestInterceptor, "post_get_aws_server_config") as post, \ - mock.patch.object(transports.AwsClustersRestInterceptor, "pre_get_aws_server_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = aws_service.GetAwsServerConfigRequest.pb(aws_service.GetAwsServerConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = aws_resources.AwsServerConfig.to_json(aws_resources.AwsServerConfig()) - req.return_value.content = return_value - - request = aws_service.GetAwsServerConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = aws_resources.AwsServerConfig() - - client.get_aws_server_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = AwsClustersClient( - 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(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 = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - 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(request_type=operations_pb2.DeleteOperationRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = AwsClustersClient( - 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(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 = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - 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(request_type=operations_pb2.GetOperationRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = AwsClustersClient( - 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(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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - 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(request_type=operations_pb2.ListOperationsRequest): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = AwsClustersClient( - 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(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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_initialize_client_w_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_aws_cluster_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_cluster), - '__call__') as call: - client.create_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.CreateAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_aws_cluster_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_cluster), - '__call__') as call: - client.update_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.UpdateAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_aws_cluster_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_cluster), - '__call__') as call: - client.get_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_aws_clusters_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_clusters), - '__call__') as call: - client.list_aws_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.ListAwsClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_aws_cluster_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_cluster), - '__call__') as call: - client.delete_aws_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.DeleteAwsClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_aws_cluster_agent_token_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_cluster_agent_token), - '__call__') as call: - client.generate_aws_cluster_agent_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GenerateAwsClusterAgentTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_aws_access_token_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_aws_access_token), - '__call__') as call: - client.generate_aws_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GenerateAwsAccessTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_aws_node_pool_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_aws_node_pool), - '__call__') as call: - client.create_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.CreateAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_aws_node_pool_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_aws_node_pool), - '__call__') as call: - client.update_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.UpdateAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_rollback_aws_node_pool_update_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.rollback_aws_node_pool_update), - '__call__') as call: - client.rollback_aws_node_pool_update(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.RollbackAwsNodePoolUpdateRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_aws_node_pool_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_node_pool), - '__call__') as call: - client.get_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_aws_node_pools_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_aws_node_pools), - '__call__') as call: - client.list_aws_node_pools(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.ListAwsNodePoolsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_aws_node_pool_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_aws_node_pool), - '__call__') as call: - client.delete_aws_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.DeleteAwsNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_aws_open_id_config_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_open_id_config), - '__call__') as call: - client.get_aws_open_id_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsOpenIdConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_aws_json_web_keys_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_json_web_keys), - '__call__') as call: - client.get_aws_json_web_keys(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsJsonWebKeysRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_aws_server_config_empty_call_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_aws_server_config), - '__call__') as call: - client.get_aws_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = aws_service.GetAwsServerConfigRequest() - - assert args[0] == request_msg - - -def test_aws_clusters_rest_lro_client(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have an 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 - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AwsClustersGrpcTransport, - ) - -def test_aws_clusters_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AwsClustersTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_aws_clusters_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.gke_multicloud_v1.services.aws_clusters.transports.AwsClustersTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AwsClustersTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_aws_cluster', - 'update_aws_cluster', - 'get_aws_cluster', - 'list_aws_clusters', - 'delete_aws_cluster', - 'generate_aws_cluster_agent_token', - 'generate_aws_access_token', - 'create_aws_node_pool', - 'update_aws_node_pool', - 'rollback_aws_node_pool_update', - 'get_aws_node_pool', - 'list_aws_node_pools', - 'delete_aws_node_pool', - 'get_aws_open_id_config', - 'get_aws_json_web_keys', - 'get_aws_server_config', - '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_aws_clusters_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.gke_multicloud_v1.services.aws_clusters.transports.AwsClustersTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AwsClustersTransport( - 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_aws_clusters_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.gke_multicloud_v1.services.aws_clusters.transports.AwsClustersTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AwsClustersTransport() - adc.assert_called_once() - - -def test_aws_clusters_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) - AwsClustersClient() - 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.AwsClustersGrpcTransport, - transports.AwsClustersGrpcAsyncIOTransport, - ], -) -def test_aws_clusters_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.AwsClustersGrpcTransport, - transports.AwsClustersGrpcAsyncIOTransport, - transports.AwsClustersRestTransport, - ], -) -def test_aws_clusters_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.AwsClustersGrpcTransport, grpc_helpers), - (transports.AwsClustersGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_aws_clusters_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( - "gkemulticloud.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="gkemulticloud.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AwsClustersGrpcTransport, transports.AwsClustersGrpcAsyncIOTransport]) -def test_aws_clusters_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_aws_clusters_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.AwsClustersRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_aws_clusters_host_no_port(transport_name): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'gkemulticloud.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://gkemulticloud.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_aws_clusters_host_with_port(transport_name): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'gkemulticloud.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://gkemulticloud.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_aws_clusters_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AwsClustersClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AwsClustersClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_aws_cluster._session - session2 = client2.transport.create_aws_cluster._session - assert session1 != session2 - session1 = client1.transport.update_aws_cluster._session - session2 = client2.transport.update_aws_cluster._session - assert session1 != session2 - session1 = client1.transport.get_aws_cluster._session - session2 = client2.transport.get_aws_cluster._session - assert session1 != session2 - session1 = client1.transport.list_aws_clusters._session - session2 = client2.transport.list_aws_clusters._session - assert session1 != session2 - session1 = client1.transport.delete_aws_cluster._session - session2 = client2.transport.delete_aws_cluster._session - assert session1 != session2 - session1 = client1.transport.generate_aws_cluster_agent_token._session - session2 = client2.transport.generate_aws_cluster_agent_token._session - assert session1 != session2 - session1 = client1.transport.generate_aws_access_token._session - session2 = client2.transport.generate_aws_access_token._session - assert session1 != session2 - session1 = client1.transport.create_aws_node_pool._session - session2 = client2.transport.create_aws_node_pool._session - assert session1 != session2 - session1 = client1.transport.update_aws_node_pool._session - session2 = client2.transport.update_aws_node_pool._session - assert session1 != session2 - session1 = client1.transport.rollback_aws_node_pool_update._session - session2 = client2.transport.rollback_aws_node_pool_update._session - assert session1 != session2 - session1 = client1.transport.get_aws_node_pool._session - session2 = client2.transport.get_aws_node_pool._session - assert session1 != session2 - session1 = client1.transport.list_aws_node_pools._session - session2 = client2.transport.list_aws_node_pools._session - assert session1 != session2 - session1 = client1.transport.delete_aws_node_pool._session - session2 = client2.transport.delete_aws_node_pool._session - assert session1 != session2 - session1 = client1.transport.get_aws_open_id_config._session - session2 = client2.transport.get_aws_open_id_config._session - assert session1 != session2 - session1 = client1.transport.get_aws_json_web_keys._session - session2 = client2.transport.get_aws_json_web_keys._session - assert session1 != session2 - session1 = client1.transport.get_aws_server_config._session - session2 = client2.transport.get_aws_server_config._session - assert session1 != session2 -def test_aws_clusters_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AwsClustersGrpcTransport( - 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_aws_clusters_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AwsClustersGrpcAsyncIOTransport( - 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.AwsClustersGrpcTransport, transports.AwsClustersGrpcAsyncIOTransport]) -def test_aws_clusters_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.AwsClustersGrpcTransport, transports.AwsClustersGrpcAsyncIOTransport]) -def test_aws_clusters_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_aws_clusters_grpc_lro_client(): - client = AwsClustersClient( - 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_aws_clusters_grpc_lro_async_client(): - client = AwsClustersAsyncClient( - 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_aws_cluster_path(): - project = "squid" - location = "clam" - aws_cluster = "whelk" - expected = "projects/{project}/locations/{location}/awsClusters/{aws_cluster}".format(project=project, location=location, aws_cluster=aws_cluster, ) - actual = AwsClustersClient.aws_cluster_path(project, location, aws_cluster) - assert expected == actual - - -def test_parse_aws_cluster_path(): - expected = { - "project": "octopus", - "location": "oyster", - "aws_cluster": "nudibranch", - } - path = AwsClustersClient.aws_cluster_path(**expected) - - # Check that the path construction is reversible. - actual = AwsClustersClient.parse_aws_cluster_path(path) - assert expected == actual - -def test_aws_node_pool_path(): - project = "cuttlefish" - location = "mussel" - aws_cluster = "winkle" - aws_node_pool = "nautilus" - expected = "projects/{project}/locations/{location}/awsClusters/{aws_cluster}/awsNodePools/{aws_node_pool}".format(project=project, location=location, aws_cluster=aws_cluster, aws_node_pool=aws_node_pool, ) - actual = AwsClustersClient.aws_node_pool_path(project, location, aws_cluster, aws_node_pool) - assert expected == actual - - -def test_parse_aws_node_pool_path(): - expected = { - "project": "scallop", - "location": "abalone", - "aws_cluster": "squid", - "aws_node_pool": "clam", - } - path = AwsClustersClient.aws_node_pool_path(**expected) - - # Check that the path construction is reversible. - actual = AwsClustersClient.parse_aws_node_pool_path(path) - assert expected == actual - -def test_aws_server_config_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}/awsServerConfig".format(project=project, location=location, ) - actual = AwsClustersClient.aws_server_config_path(project, location) - assert expected == actual - - -def test_parse_aws_server_config_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = AwsClustersClient.aws_server_config_path(**expected) - - # Check that the path construction is reversible. - actual = AwsClustersClient.parse_aws_server_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AwsClustersClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = AwsClustersClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AwsClustersClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = AwsClustersClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = AwsClustersClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AwsClustersClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AwsClustersClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = AwsClustersClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AwsClustersClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = AwsClustersClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = AwsClustersClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AwsClustersClient.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 = AwsClustersClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = AwsClustersClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AwsClustersClient.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.AwsClustersTransport, '_prep_wrapped_messages') as prep: - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AwsClustersTransport, '_prep_wrapped_messages') as prep: - transport_class = AwsClustersClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_delete_operation(transport: str = "grpc"): - client = AwsClustersClient( - 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_asyncio"): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AwsClustersClient( - 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 = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AwsClustersClient( - 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 = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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 = AwsClustersClient( - 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_asyncio"): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AwsClustersClient( - 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 = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AwsClustersClient( - 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 = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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 = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AwsClustersClient( - 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 = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AwsClustersClient( - 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 = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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 = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc_asyncio"): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AwsClustersClient( - 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 = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AwsClustersClient( - 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 = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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_transport_close_grpc(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = AwsClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_rest(): - client = AwsClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "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 = AwsClustersClient( - 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", [ - (AwsClustersClient, transports.AwsClustersGrpcTransport), - (AwsClustersAsyncClient, transports.AwsClustersGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_azure_clusters.py b/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_azure_clusters.py deleted file mode 100644 index bb38ff4336ea..000000000000 --- a/owl-bot-staging/google-cloud-gke-multicloud/v1/tests/unit/gapic/gke_multicloud_v1/test_azure_clusters.py +++ /dev/null @@ -1,15936 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.gke_multicloud_v1.services.azure_clusters import AzureClustersAsyncClient -from google.cloud.gke_multicloud_v1.services.azure_clusters import AzureClustersClient -from google.cloud.gke_multicloud_v1.services.azure_clusters import pagers -from google.cloud.gke_multicloud_v1.services.azure_clusters import transports -from google.cloud.gke_multicloud_v1.types import azure_resources -from google.cloud.gke_multicloud_v1.types import azure_service -from google.cloud.gke_multicloud_v1.types import common_resources -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 - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AzureClustersClient._get_default_mtls_endpoint(None) is None - assert AzureClustersClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AzureClustersClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AzureClustersClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AzureClustersClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AzureClustersClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AzureClustersClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AzureClustersClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AzureClustersClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AzureClustersClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert AzureClustersClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AzureClustersClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AzureClustersClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AzureClustersClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert AzureClustersClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert AzureClustersClient._get_client_cert_source(None, False) is None - assert AzureClustersClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AzureClustersClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert AzureClustersClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AzureClustersClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AzureClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersClient)) -@mock.patch.object(AzureClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AzureClustersClient._DEFAULT_UNIVERSE - default_endpoint = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AzureClustersClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AzureClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AzureClustersClient.DEFAULT_MTLS_ENDPOINT - assert AzureClustersClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AzureClustersClient._get_api_endpoint(None, None, default_universe, "always") == AzureClustersClient.DEFAULT_MTLS_ENDPOINT - assert AzureClustersClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AzureClustersClient.DEFAULT_MTLS_ENDPOINT - assert AzureClustersClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AzureClustersClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AzureClustersClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert AzureClustersClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AzureClustersClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AzureClustersClient._get_universe_domain(None, None) == AzureClustersClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AzureClustersClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AzureClustersClient, "grpc"), - (AzureClustersAsyncClient, "grpc_asyncio"), - (AzureClustersClient, "rest"), -]) -def test_azure_clusters_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 == ( - 'gkemulticloud.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://gkemulticloud.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AzureClustersGrpcTransport, "grpc"), - (transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AzureClustersRestTransport, "rest"), -]) -def test_azure_clusters_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", [ - (AzureClustersClient, "grpc"), - (AzureClustersAsyncClient, "grpc_asyncio"), - (AzureClustersClient, "rest"), -]) -def test_azure_clusters_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 == ( - 'gkemulticloud.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://gkemulticloud.googleapis.com' - ) - - -def test_azure_clusters_client_get_transport_class(): - transport = AzureClustersClient.get_transport_class() - available_transports = [ - transports.AzureClustersGrpcTransport, - transports.AzureClustersRestTransport, - ] - assert transport in available_transports - - transport = AzureClustersClient.get_transport_class("grpc") - assert transport == transports.AzureClustersGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc"), - (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio"), - (AzureClustersClient, transports.AzureClustersRestTransport, "rest"), -]) -@mock.patch.object(AzureClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersClient)) -@mock.patch.object(AzureClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersAsyncClient)) -def test_azure_clusters_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(AzureClustersClient, '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(AzureClustersClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc", "true"), - (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc", "false"), - (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AzureClustersClient, transports.AzureClustersRestTransport, "rest", "true"), - (AzureClustersClient, transports.AzureClustersRestTransport, "rest", "false"), -]) -@mock.patch.object(AzureClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersClient)) -@mock.patch.object(AzureClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_azure_clusters_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - AzureClustersClient, AzureClustersAsyncClient -]) -@mock.patch.object(AzureClustersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AzureClustersClient)) -@mock.patch.object(AzureClustersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AzureClustersAsyncClient)) -def test_azure_clusters_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - AzureClustersClient, AzureClustersAsyncClient -]) -@mock.patch.object(AzureClustersClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersClient)) -@mock.patch.object(AzureClustersAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AzureClustersAsyncClient)) -def test_azure_clusters_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AzureClustersClient._DEFAULT_UNIVERSE - default_endpoint = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AzureClustersClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc"), - (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio"), - (AzureClustersClient, transports.AzureClustersRestTransport, "rest"), -]) -def test_azure_clusters_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc", grpc_helpers), - (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AzureClustersClient, transports.AzureClustersRestTransport, "rest", None), -]) -def test_azure_clusters_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_azure_clusters_client_client_options_from_dict(): - with mock.patch('google.cloud.gke_multicloud_v1.services.azure_clusters.transports.AzureClustersGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AzureClustersClient( - 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", [ - (AzureClustersClient, transports.AzureClustersGrpcTransport, "grpc", grpc_helpers), - (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_azure_clusters_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "gkemulticloud.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="gkemulticloud.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.CreateAzureClientRequest, - dict, -]) -def test_create_azure_client(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_client), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.CreateAzureClientRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_azure_client_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.CreateAzureClientRequest( - parent='parent_value', - azure_client_id='azure_client_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_client), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_azure_client(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.CreateAzureClientRequest( - parent='parent_value', - azure_client_id='azure_client_id_value', - ) - -def test_create_azure_client_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_azure_client in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_azure_client] = mock_rpc - request = {} - client.create_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_azure_client(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_azure_client_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_azure_client in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_azure_client] = mock_rpc - - request = {} - await client.create_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_azure_client(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_azure_client_async(transport: str = 'grpc_asyncio', request_type=azure_service.CreateAzureClientRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_client), - '__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_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.CreateAzureClientRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_azure_client_async_from_dict(): - await test_create_azure_client_async(request_type=dict) - -def test_create_azure_client_field_headers(): - client = AzureClustersClient( - 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 = azure_service.CreateAzureClientRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_client), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_azure_client(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_azure_client_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.CreateAzureClientRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_client), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_azure_client(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_azure_client_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_client), - '__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_azure_client( - parent='parent_value', - azure_client=azure_resources.AzureClient(name='name_value'), - azure_client_id='azure_client_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].azure_client - mock_val = azure_resources.AzureClient(name='name_value') - assert arg == mock_val - arg = args[0].azure_client_id - mock_val = 'azure_client_id_value' - assert arg == mock_val - - -def test_create_azure_client_flattened_error(): - client = AzureClustersClient( - 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_azure_client( - azure_service.CreateAzureClientRequest(), - parent='parent_value', - azure_client=azure_resources.AzureClient(name='name_value'), - azure_client_id='azure_client_id_value', - ) - -@pytest.mark.asyncio -async def test_create_azure_client_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_client), - '__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_azure_client( - parent='parent_value', - azure_client=azure_resources.AzureClient(name='name_value'), - azure_client_id='azure_client_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].azure_client - mock_val = azure_resources.AzureClient(name='name_value') - assert arg == mock_val - arg = args[0].azure_client_id - mock_val = 'azure_client_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_azure_client_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_azure_client( - azure_service.CreateAzureClientRequest(), - parent='parent_value', - azure_client=azure_resources.AzureClient(name='name_value'), - azure_client_id='azure_client_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureClientRequest, - dict, -]) -def test_get_azure_client(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_client), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureClient( - name='name_value', - tenant_id='tenant_id_value', - application_id='application_id_value', - reconciling=True, - pem_certificate='pem_certificate_value', - uid='uid_value', - ) - response = client.get_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureClientRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureClient) - assert response.name == 'name_value' - assert response.tenant_id == 'tenant_id_value' - assert response.application_id == 'application_id_value' - assert response.reconciling is True - assert response.pem_certificate == 'pem_certificate_value' - assert response.uid == 'uid_value' - - -def test_get_azure_client_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.GetAzureClientRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_client), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_azure_client(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.GetAzureClientRequest( - name='name_value', - ) - -def test_get_azure_client_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_client in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_client] = mock_rpc - request = {} - client.get_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_client(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_client_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_azure_client in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_azure_client] = mock_rpc - - request = {} - await client.get_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_azure_client(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_client_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureClientRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_client), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureClient( - name='name_value', - tenant_id='tenant_id_value', - application_id='application_id_value', - reconciling=True, - pem_certificate='pem_certificate_value', - uid='uid_value', - )) - response = await client.get_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureClientRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureClient) - assert response.name == 'name_value' - assert response.tenant_id == 'tenant_id_value' - assert response.application_id == 'application_id_value' - assert response.reconciling is True - assert response.pem_certificate == 'pem_certificate_value' - assert response.uid == 'uid_value' - - -@pytest.mark.asyncio -async def test_get_azure_client_async_from_dict(): - await test_get_azure_client_async(request_type=dict) - -def test_get_azure_client_field_headers(): - client = AzureClustersClient( - 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 = azure_service.GetAzureClientRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_client), - '__call__') as call: - call.return_value = azure_resources.AzureClient() - client.get_azure_client(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_azure_client_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.GetAzureClientRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_client), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureClient()) - await client.get_azure_client(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_azure_client_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_client), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureClient() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_azure_client( - 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_azure_client_flattened_error(): - client = AzureClustersClient( - 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_azure_client( - azure_service.GetAzureClientRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_azure_client_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_client), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureClient() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureClient()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_azure_client( - 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_azure_client_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_azure_client( - azure_service.GetAzureClientRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.ListAzureClientsRequest, - dict, -]) -def test_list_azure_clients(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_clients), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.ListAzureClientsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_azure_clients(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.ListAzureClientsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAzureClientsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_azure_clients_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.ListAzureClientsRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clients), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_azure_clients(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.ListAzureClientsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_azure_clients_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_azure_clients in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_azure_clients] = mock_rpc - request = {} - client.list_azure_clients(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_azure_clients(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_azure_clients_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_azure_clients in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_azure_clients] = mock_rpc - - request = {} - await client.list_azure_clients(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_azure_clients(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_azure_clients_async(transport: str = 'grpc_asyncio', request_type=azure_service.ListAzureClientsRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_clients), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClientsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_azure_clients(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.ListAzureClientsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAzureClientsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_azure_clients_async_from_dict(): - await test_list_azure_clients_async(request_type=dict) - -def test_list_azure_clients_field_headers(): - client = AzureClustersClient( - 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 = azure_service.ListAzureClientsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clients), - '__call__') as call: - call.return_value = azure_service.ListAzureClientsResponse() - client.list_azure_clients(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_azure_clients_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.ListAzureClientsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clients), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClientsResponse()) - await client.list_azure_clients(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_azure_clients_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clients), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.ListAzureClientsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_azure_clients( - 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_azure_clients_flattened_error(): - client = AzureClustersClient( - 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_azure_clients( - azure_service.ListAzureClientsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_azure_clients_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clients), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.ListAzureClientsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClientsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_azure_clients( - 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_azure_clients_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_azure_clients( - azure_service.ListAzureClientsRequest(), - parent='parent_value', - ) - - -def test_list_azure_clients_pager(transport_name: str = "grpc"): - client = AzureClustersClient( - 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_azure_clients), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - azure_resources.AzureClient(), - azure_resources.AzureClient(), - ], - next_page_token='abc', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[], - next_page_token='def', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - azure_resources.AzureClient(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_azure_clients(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, azure_resources.AzureClient) - for i in results) -def test_list_azure_clients_pages(transport_name: str = "grpc"): - client = AzureClustersClient( - 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_azure_clients), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - azure_resources.AzureClient(), - azure_resources.AzureClient(), - ], - next_page_token='abc', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[], - next_page_token='def', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - azure_resources.AzureClient(), - ], - ), - RuntimeError, - ) - pages = list(client.list_azure_clients(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_azure_clients_async_pager(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clients), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - azure_resources.AzureClient(), - azure_resources.AzureClient(), - ], - next_page_token='abc', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[], - next_page_token='def', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - azure_resources.AzureClient(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_azure_clients(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, azure_resources.AzureClient) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_azure_clients_async_pages(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clients), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - azure_resources.AzureClient(), - azure_resources.AzureClient(), - ], - next_page_token='abc', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[], - next_page_token='def', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - azure_resources.AzureClient(), - ], - ), - 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_azure_clients(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", [ - azure_service.DeleteAzureClientRequest, - dict, -]) -def test_delete_azure_client(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_client), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.DeleteAzureClientRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_azure_client_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.DeleteAzureClientRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_client), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_azure_client(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.DeleteAzureClientRequest( - name='name_value', - ) - -def test_delete_azure_client_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_azure_client in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_azure_client] = mock_rpc - request = {} - client.delete_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_azure_client(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_azure_client_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_azure_client in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_azure_client] = mock_rpc - - request = {} - await client.delete_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_azure_client(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_azure_client_async(transport: str = 'grpc_asyncio', request_type=azure_service.DeleteAzureClientRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_client), - '__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_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.DeleteAzureClientRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_azure_client_async_from_dict(): - await test_delete_azure_client_async(request_type=dict) - -def test_delete_azure_client_field_headers(): - client = AzureClustersClient( - 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 = azure_service.DeleteAzureClientRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_client), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_azure_client(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_azure_client_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.DeleteAzureClientRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_client), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_azure_client(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_azure_client_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_client), - '__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_azure_client( - 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_azure_client_flattened_error(): - client = AzureClustersClient( - 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_azure_client( - azure_service.DeleteAzureClientRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_azure_client_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_client), - '__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_azure_client( - 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_azure_client_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_azure_client( - azure_service.DeleteAzureClientRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.CreateAzureClusterRequest, - dict, -]) -def test_create_azure_cluster(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.CreateAzureClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_azure_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.CreateAzureClusterRequest( - parent='parent_value', - azure_cluster_id='azure_cluster_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_azure_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.CreateAzureClusterRequest( - parent='parent_value', - azure_cluster_id='azure_cluster_id_value', - ) - -def test_create_azure_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_azure_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_azure_cluster] = mock_rpc - request = {} - client.create_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_azure_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_azure_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_azure_cluster] = mock_rpc - - request = {} - await client.create_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_azure_cluster_async(transport: str = 'grpc_asyncio', request_type=azure_service.CreateAzureClusterRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_cluster), - '__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_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.CreateAzureClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_azure_cluster_async_from_dict(): - await test_create_azure_cluster_async(request_type=dict) - -def test_create_azure_cluster_field_headers(): - client = AzureClustersClient( - 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 = azure_service.CreateAzureClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_azure_cluster(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_azure_cluster_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.CreateAzureClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_azure_cluster(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_azure_cluster_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_cluster), - '__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_azure_cluster( - parent='parent_value', - azure_cluster=azure_resources.AzureCluster(name='name_value'), - azure_cluster_id='azure_cluster_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].azure_cluster - mock_val = azure_resources.AzureCluster(name='name_value') - assert arg == mock_val - arg = args[0].azure_cluster_id - mock_val = 'azure_cluster_id_value' - assert arg == mock_val - - -def test_create_azure_cluster_flattened_error(): - client = AzureClustersClient( - 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_azure_cluster( - azure_service.CreateAzureClusterRequest(), - parent='parent_value', - azure_cluster=azure_resources.AzureCluster(name='name_value'), - azure_cluster_id='azure_cluster_id_value', - ) - -@pytest.mark.asyncio -async def test_create_azure_cluster_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_cluster), - '__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_azure_cluster( - parent='parent_value', - azure_cluster=azure_resources.AzureCluster(name='name_value'), - azure_cluster_id='azure_cluster_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].azure_cluster - mock_val = azure_resources.AzureCluster(name='name_value') - assert arg == mock_val - arg = args[0].azure_cluster_id - mock_val = 'azure_cluster_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_azure_cluster_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_azure_cluster( - azure_service.CreateAzureClusterRequest(), - parent='parent_value', - azure_cluster=azure_resources.AzureCluster(name='name_value'), - azure_cluster_id='azure_cluster_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.UpdateAzureClusterRequest, - dict, -]) -def test_update_azure_cluster(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.UpdateAzureClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_azure_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.UpdateAzureClusterRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_azure_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.UpdateAzureClusterRequest( - ) - -def test_update_azure_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_azure_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_azure_cluster] = mock_rpc - request = {} - client.update_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_azure_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_azure_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_azure_cluster] = mock_rpc - - request = {} - await client.update_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_azure_cluster_async(transport: str = 'grpc_asyncio', request_type=azure_service.UpdateAzureClusterRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_cluster), - '__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_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.UpdateAzureClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_azure_cluster_async_from_dict(): - await test_update_azure_cluster_async(request_type=dict) - -def test_update_azure_cluster_field_headers(): - client = AzureClustersClient( - 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 = azure_service.UpdateAzureClusterRequest() - - request.azure_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_azure_cluster(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', - 'azure_cluster.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_azure_cluster_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.UpdateAzureClusterRequest() - - request.azure_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_azure_cluster(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', - 'azure_cluster.name=name_value', - ) in kw['metadata'] - - -def test_update_azure_cluster_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_cluster), - '__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_azure_cluster( - azure_cluster=azure_resources.AzureCluster(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].azure_cluster - mock_val = azure_resources.AzureCluster(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_azure_cluster_flattened_error(): - client = AzureClustersClient( - 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_azure_cluster( - azure_service.UpdateAzureClusterRequest(), - azure_cluster=azure_resources.AzureCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_azure_cluster_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_cluster), - '__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_azure_cluster( - azure_cluster=azure_resources.AzureCluster(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].azure_cluster - mock_val = azure_resources.AzureCluster(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_azure_cluster_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_azure_cluster( - azure_service.UpdateAzureClusterRequest(), - azure_cluster=azure_resources.AzureCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureClusterRequest, - dict, -]) -def test_get_azure_cluster(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureCluster( - name='name_value', - description='description_value', - azure_region='azure_region_value', - resource_group_id='resource_group_id_value', - azure_client='azure_client_value', - state=azure_resources.AzureCluster.State.PROVISIONING, - endpoint='endpoint_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - cluster_ca_certificate='cluster_ca_certificate_value', - ) - response = client.get_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureCluster) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.azure_region == 'azure_region_value' - assert response.resource_group_id == 'resource_group_id_value' - assert response.azure_client == 'azure_client_value' - assert response.state == azure_resources.AzureCluster.State.PROVISIONING - assert response.endpoint == 'endpoint_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' - - -def test_get_azure_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.GetAzureClusterRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_azure_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.GetAzureClusterRequest( - name='name_value', - ) - -def test_get_azure_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_cluster] = mock_rpc - request = {} - client.get_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_azure_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_azure_cluster] = mock_rpc - - request = {} - await client.get_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_cluster_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureClusterRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureCluster( - name='name_value', - description='description_value', - azure_region='azure_region_value', - resource_group_id='resource_group_id_value', - azure_client='azure_client_value', - state=azure_resources.AzureCluster.State.PROVISIONING, - endpoint='endpoint_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - cluster_ca_certificate='cluster_ca_certificate_value', - )) - response = await client.get_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureCluster) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.azure_region == 'azure_region_value' - assert response.resource_group_id == 'resource_group_id_value' - assert response.azure_client == 'azure_client_value' - assert response.state == azure_resources.AzureCluster.State.PROVISIONING - assert response.endpoint == 'endpoint_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' - - -@pytest.mark.asyncio -async def test_get_azure_cluster_async_from_dict(): - await test_get_azure_cluster_async(request_type=dict) - -def test_get_azure_cluster_field_headers(): - client = AzureClustersClient( - 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 = azure_service.GetAzureClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_cluster), - '__call__') as call: - call.return_value = azure_resources.AzureCluster() - client.get_azure_cluster(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_azure_cluster_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.GetAzureClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureCluster()) - await client.get_azure_cluster(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_azure_cluster_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureCluster() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_azure_cluster( - 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_azure_cluster_flattened_error(): - client = AzureClustersClient( - 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_azure_cluster( - azure_service.GetAzureClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_azure_cluster_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureCluster() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureCluster()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_azure_cluster( - 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_azure_cluster_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_azure_cluster( - azure_service.GetAzureClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.ListAzureClustersRequest, - dict, -]) -def test_list_azure_clusters(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.ListAzureClustersResponse( - next_page_token='next_page_token_value', - ) - response = client.list_azure_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.ListAzureClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAzureClustersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_azure_clusters_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.ListAzureClustersRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clusters), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_azure_clusters(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.ListAzureClustersRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_azure_clusters_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_azure_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_azure_clusters] = mock_rpc - request = {} - client.list_azure_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_azure_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_azure_clusters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_azure_clusters in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_azure_clusters] = mock_rpc - - request = {} - await client.list_azure_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_azure_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_azure_clusters_async(transport: str = 'grpc_asyncio', request_type=azure_service.ListAzureClustersRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClustersResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_azure_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.ListAzureClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAzureClustersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_azure_clusters_async_from_dict(): - await test_list_azure_clusters_async(request_type=dict) - -def test_list_azure_clusters_field_headers(): - client = AzureClustersClient( - 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 = azure_service.ListAzureClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clusters), - '__call__') as call: - call.return_value = azure_service.ListAzureClustersResponse() - client.list_azure_clusters(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_azure_clusters_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.ListAzureClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clusters), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClustersResponse()) - await client.list_azure_clusters(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_azure_clusters_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.ListAzureClustersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_azure_clusters( - 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_azure_clusters_flattened_error(): - client = AzureClustersClient( - 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_azure_clusters( - azure_service.ListAzureClustersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_azure_clusters_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.ListAzureClustersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClustersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_azure_clusters( - 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_azure_clusters_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_azure_clusters( - azure_service.ListAzureClustersRequest(), - parent='parent_value', - ) - - -def test_list_azure_clusters_pager(transport_name: str = "grpc"): - client = AzureClustersClient( - 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_azure_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - ], - next_page_token='abc', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[], - next_page_token='def', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_azure_clusters(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, azure_resources.AzureCluster) - for i in results) -def test_list_azure_clusters_pages(transport_name: str = "grpc"): - client = AzureClustersClient( - 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_azure_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - ], - next_page_token='abc', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[], - next_page_token='def', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - ], - ), - RuntimeError, - ) - pages = list(client.list_azure_clusters(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_azure_clusters_async_pager(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - ], - next_page_token='abc', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[], - next_page_token='def', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_azure_clusters(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, azure_resources.AzureCluster) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_azure_clusters_async_pages(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - ], - next_page_token='abc', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[], - next_page_token='def', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - ], - ), - 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_azure_clusters(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", [ - azure_service.DeleteAzureClusterRequest, - dict, -]) -def test_delete_azure_cluster(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.DeleteAzureClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_azure_cluster_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.DeleteAzureClusterRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_azure_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.DeleteAzureClusterRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_azure_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_azure_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_azure_cluster] = mock_rpc - request = {} - client.delete_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_azure_cluster_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_azure_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_azure_cluster] = mock_rpc - - request = {} - await client.delete_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_azure_cluster_async(transport: str = 'grpc_asyncio', request_type=azure_service.DeleteAzureClusterRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_cluster), - '__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_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.DeleteAzureClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_azure_cluster_async_from_dict(): - await test_delete_azure_cluster_async(request_type=dict) - -def test_delete_azure_cluster_field_headers(): - client = AzureClustersClient( - 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 = azure_service.DeleteAzureClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_azure_cluster(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_azure_cluster_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.DeleteAzureClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_azure_cluster(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_azure_cluster_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_cluster), - '__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_azure_cluster( - 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_azure_cluster_flattened_error(): - client = AzureClustersClient( - 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_azure_cluster( - azure_service.DeleteAzureClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_azure_cluster_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_cluster), - '__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_azure_cluster( - 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_azure_cluster_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_azure_cluster( - azure_service.DeleteAzureClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GenerateAzureClusterAgentTokenRequest, - dict, -]) -def test_generate_azure_cluster_agent_token(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_cluster_agent_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.GenerateAzureClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - ) - response = client.generate_azure_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.GenerateAzureClusterAgentTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_service.GenerateAzureClusterAgentTokenResponse) - assert response.access_token == 'access_token_value' - assert response.expires_in == 1078 - assert response.token_type == 'token_type_value' - - -def test_generate_azure_cluster_agent_token_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.GenerateAzureClusterAgentTokenRequest( - azure_cluster='azure_cluster_value', - subject_token='subject_token_value', - subject_token_type='subject_token_type_value', - version='version_value', - node_pool_id='node_pool_id_value', - grant_type='grant_type_value', - audience='audience_value', - scope='scope_value', - requested_token_type='requested_token_type_value', - options='options_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_cluster_agent_token), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_azure_cluster_agent_token(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.GenerateAzureClusterAgentTokenRequest( - azure_cluster='azure_cluster_value', - subject_token='subject_token_value', - subject_token_type='subject_token_type_value', - version='version_value', - node_pool_id='node_pool_id_value', - grant_type='grant_type_value', - audience='audience_value', - scope='scope_value', - requested_token_type='requested_token_type_value', - options='options_value', - ) - -def test_generate_azure_cluster_agent_token_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_azure_cluster_agent_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_azure_cluster_agent_token] = mock_rpc - request = {} - client.generate_azure_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_azure_cluster_agent_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_azure_cluster_agent_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_azure_cluster_agent_token in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_azure_cluster_agent_token] = mock_rpc - - request = {} - await client.generate_azure_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_azure_cluster_agent_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_azure_cluster_agent_token_async(transport: str = 'grpc_asyncio', request_type=azure_service.GenerateAzureClusterAgentTokenRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_cluster_agent_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - )) - response = await client.generate_azure_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.GenerateAzureClusterAgentTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_service.GenerateAzureClusterAgentTokenResponse) - assert response.access_token == 'access_token_value' - assert response.expires_in == 1078 - assert response.token_type == 'token_type_value' - - -@pytest.mark.asyncio -async def test_generate_azure_cluster_agent_token_async_from_dict(): - await test_generate_azure_cluster_agent_token_async(request_type=dict) - -def test_generate_azure_cluster_agent_token_field_headers(): - client = AzureClustersClient( - 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 = azure_service.GenerateAzureClusterAgentTokenRequest() - - request.azure_cluster = 'azure_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_cluster_agent_token), - '__call__') as call: - call.return_value = azure_service.GenerateAzureClusterAgentTokenResponse() - client.generate_azure_cluster_agent_token(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', - 'azure_cluster=azure_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_azure_cluster_agent_token_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.GenerateAzureClusterAgentTokenRequest() - - request.azure_cluster = 'azure_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_cluster_agent_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureClusterAgentTokenResponse()) - await client.generate_azure_cluster_agent_token(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', - 'azure_cluster=azure_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - azure_service.GenerateAzureAccessTokenRequest, - dict, -]) -def test_generate_azure_access_token(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.GenerateAzureAccessTokenResponse( - access_token='access_token_value', - ) - response = client.generate_azure_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.GenerateAzureAccessTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_service.GenerateAzureAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -def test_generate_azure_access_token_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.GenerateAzureAccessTokenRequest( - azure_cluster='azure_cluster_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_access_token), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_azure_access_token(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.GenerateAzureAccessTokenRequest( - azure_cluster='azure_cluster_value', - ) - -def test_generate_azure_access_token_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_azure_access_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_azure_access_token] = mock_rpc - request = {} - client.generate_azure_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_azure_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_azure_access_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_azure_access_token in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_azure_access_token] = mock_rpc - - request = {} - await client.generate_azure_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_azure_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_azure_access_token_async(transport: str = 'grpc_asyncio', request_type=azure_service.GenerateAzureAccessTokenRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureAccessTokenResponse( - access_token='access_token_value', - )) - response = await client.generate_azure_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.GenerateAzureAccessTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_service.GenerateAzureAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.asyncio -async def test_generate_azure_access_token_async_from_dict(): - await test_generate_azure_access_token_async(request_type=dict) - -def test_generate_azure_access_token_field_headers(): - client = AzureClustersClient( - 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 = azure_service.GenerateAzureAccessTokenRequest() - - request.azure_cluster = 'azure_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_access_token), - '__call__') as call: - call.return_value = azure_service.GenerateAzureAccessTokenResponse() - client.generate_azure_access_token(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', - 'azure_cluster=azure_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_azure_access_token_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.GenerateAzureAccessTokenRequest() - - request.azure_cluster = 'azure_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_access_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureAccessTokenResponse()) - await client.generate_azure_access_token(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', - 'azure_cluster=azure_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - azure_service.CreateAzureNodePoolRequest, - dict, -]) -def test_create_azure_node_pool(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.CreateAzureNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_azure_node_pool_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.CreateAzureNodePoolRequest( - parent='parent_value', - azure_node_pool_id='azure_node_pool_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_azure_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.CreateAzureNodePoolRequest( - parent='parent_value', - azure_node_pool_id='azure_node_pool_id_value', - ) - -def test_create_azure_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_azure_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_azure_node_pool] = mock_rpc - request = {} - client.create_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_azure_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_azure_node_pool in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_azure_node_pool] = mock_rpc - - request = {} - await client.create_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_azure_node_pool_async(transport: str = 'grpc_asyncio', request_type=azure_service.CreateAzureNodePoolRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_node_pool), - '__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_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.CreateAzureNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_azure_node_pool_async_from_dict(): - await test_create_azure_node_pool_async(request_type=dict) - -def test_create_azure_node_pool_field_headers(): - client = AzureClustersClient( - 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 = azure_service.CreateAzureNodePoolRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_azure_node_pool(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_azure_node_pool_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.CreateAzureNodePoolRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_azure_node_pool(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_azure_node_pool_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_node_pool), - '__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_azure_node_pool( - parent='parent_value', - azure_node_pool=azure_resources.AzureNodePool(name='name_value'), - azure_node_pool_id='azure_node_pool_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].azure_node_pool - mock_val = azure_resources.AzureNodePool(name='name_value') - assert arg == mock_val - arg = args[0].azure_node_pool_id - mock_val = 'azure_node_pool_id_value' - assert arg == mock_val - - -def test_create_azure_node_pool_flattened_error(): - client = AzureClustersClient( - 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_azure_node_pool( - azure_service.CreateAzureNodePoolRequest(), - parent='parent_value', - azure_node_pool=azure_resources.AzureNodePool(name='name_value'), - azure_node_pool_id='azure_node_pool_id_value', - ) - -@pytest.mark.asyncio -async def test_create_azure_node_pool_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_node_pool), - '__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_azure_node_pool( - parent='parent_value', - azure_node_pool=azure_resources.AzureNodePool(name='name_value'), - azure_node_pool_id='azure_node_pool_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].azure_node_pool - mock_val = azure_resources.AzureNodePool(name='name_value') - assert arg == mock_val - arg = args[0].azure_node_pool_id - mock_val = 'azure_node_pool_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_azure_node_pool_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_azure_node_pool( - azure_service.CreateAzureNodePoolRequest(), - parent='parent_value', - azure_node_pool=azure_resources.AzureNodePool(name='name_value'), - azure_node_pool_id='azure_node_pool_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.UpdateAzureNodePoolRequest, - dict, -]) -def test_update_azure_node_pool(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.UpdateAzureNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_azure_node_pool_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.UpdateAzureNodePoolRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_azure_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.UpdateAzureNodePoolRequest( - ) - -def test_update_azure_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_azure_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_azure_node_pool] = mock_rpc - request = {} - client.update_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_azure_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_azure_node_pool in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_azure_node_pool] = mock_rpc - - request = {} - await client.update_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_azure_node_pool_async(transport: str = 'grpc_asyncio', request_type=azure_service.UpdateAzureNodePoolRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_node_pool), - '__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_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.UpdateAzureNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_azure_node_pool_async_from_dict(): - await test_update_azure_node_pool_async(request_type=dict) - -def test_update_azure_node_pool_field_headers(): - client = AzureClustersClient( - 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 = azure_service.UpdateAzureNodePoolRequest() - - request.azure_node_pool.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_azure_node_pool(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', - 'azure_node_pool.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_azure_node_pool_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.UpdateAzureNodePoolRequest() - - request.azure_node_pool.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_azure_node_pool(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', - 'azure_node_pool.name=name_value', - ) in kw['metadata'] - - -def test_update_azure_node_pool_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_node_pool), - '__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_azure_node_pool( - azure_node_pool=azure_resources.AzureNodePool(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].azure_node_pool - mock_val = azure_resources.AzureNodePool(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_azure_node_pool_flattened_error(): - client = AzureClustersClient( - 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_azure_node_pool( - azure_service.UpdateAzureNodePoolRequest(), - azure_node_pool=azure_resources.AzureNodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_azure_node_pool_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_node_pool), - '__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_azure_node_pool( - azure_node_pool=azure_resources.AzureNodePool(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].azure_node_pool - mock_val = azure_resources.AzureNodePool(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_azure_node_pool_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_azure_node_pool( - azure_service.UpdateAzureNodePoolRequest(), - azure_node_pool=azure_resources.AzureNodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureNodePoolRequest, - dict, -]) -def test_get_azure_node_pool(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureNodePool( - name='name_value', - version='version_value', - subnet_id='subnet_id_value', - state=azure_resources.AzureNodePool.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - azure_availability_zone='azure_availability_zone_value', - ) - response = client.get_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureNodePool) - assert response.name == 'name_value' - assert response.version == 'version_value' - assert response.subnet_id == 'subnet_id_value' - assert response.state == azure_resources.AzureNodePool.State.PROVISIONING - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.azure_availability_zone == 'azure_availability_zone_value' - - -def test_get_azure_node_pool_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.GetAzureNodePoolRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_azure_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.GetAzureNodePoolRequest( - name='name_value', - ) - -def test_get_azure_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_node_pool] = mock_rpc - request = {} - client.get_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_azure_node_pool in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_azure_node_pool] = mock_rpc - - request = {} - await client.get_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_node_pool_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureNodePoolRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureNodePool( - name='name_value', - version='version_value', - subnet_id='subnet_id_value', - state=azure_resources.AzureNodePool.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - azure_availability_zone='azure_availability_zone_value', - )) - response = await client.get_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureNodePool) - assert response.name == 'name_value' - assert response.version == 'version_value' - assert response.subnet_id == 'subnet_id_value' - assert response.state == azure_resources.AzureNodePool.State.PROVISIONING - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.azure_availability_zone == 'azure_availability_zone_value' - - -@pytest.mark.asyncio -async def test_get_azure_node_pool_async_from_dict(): - await test_get_azure_node_pool_async(request_type=dict) - -def test_get_azure_node_pool_field_headers(): - client = AzureClustersClient( - 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 = azure_service.GetAzureNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_node_pool), - '__call__') as call: - call.return_value = azure_resources.AzureNodePool() - client.get_azure_node_pool(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_azure_node_pool_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.GetAzureNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureNodePool()) - await client.get_azure_node_pool(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_azure_node_pool_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureNodePool() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_azure_node_pool( - 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_azure_node_pool_flattened_error(): - client = AzureClustersClient( - 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_azure_node_pool( - azure_service.GetAzureNodePoolRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_azure_node_pool_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureNodePool() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureNodePool()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_azure_node_pool( - 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_azure_node_pool_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_azure_node_pool( - azure_service.GetAzureNodePoolRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.ListAzureNodePoolsRequest, - dict, -]) -def test_list_azure_node_pools(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.ListAzureNodePoolsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_azure_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.ListAzureNodePoolsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAzureNodePoolsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_azure_node_pools_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.ListAzureNodePoolsRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_node_pools), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_azure_node_pools(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.ListAzureNodePoolsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_azure_node_pools_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_azure_node_pools in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_azure_node_pools] = mock_rpc - request = {} - client.list_azure_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_azure_node_pools(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_azure_node_pools_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_azure_node_pools in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_azure_node_pools] = mock_rpc - - request = {} - await client.list_azure_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_azure_node_pools(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_azure_node_pools_async(transport: str = 'grpc_asyncio', request_type=azure_service.ListAzureNodePoolsRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureNodePoolsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_azure_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.ListAzureNodePoolsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAzureNodePoolsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_azure_node_pools_async_from_dict(): - await test_list_azure_node_pools_async(request_type=dict) - -def test_list_azure_node_pools_field_headers(): - client = AzureClustersClient( - 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 = azure_service.ListAzureNodePoolsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_node_pools), - '__call__') as call: - call.return_value = azure_service.ListAzureNodePoolsResponse() - client.list_azure_node_pools(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_azure_node_pools_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.ListAzureNodePoolsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_node_pools), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureNodePoolsResponse()) - await client.list_azure_node_pools(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_azure_node_pools_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.ListAzureNodePoolsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_azure_node_pools( - 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_azure_node_pools_flattened_error(): - client = AzureClustersClient( - 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_azure_node_pools( - azure_service.ListAzureNodePoolsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_azure_node_pools_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_service.ListAzureNodePoolsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureNodePoolsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_azure_node_pools( - 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_azure_node_pools_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_azure_node_pools( - azure_service.ListAzureNodePoolsRequest(), - parent='parent_value', - ) - - -def test_list_azure_node_pools_pager(transport_name: str = "grpc"): - client = AzureClustersClient( - 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_azure_node_pools), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - ], - next_page_token='abc', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[], - next_page_token='def', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_azure_node_pools(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, azure_resources.AzureNodePool) - for i in results) -def test_list_azure_node_pools_pages(transport_name: str = "grpc"): - client = AzureClustersClient( - 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_azure_node_pools), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - ], - next_page_token='abc', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[], - next_page_token='def', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - ], - ), - RuntimeError, - ) - pages = list(client.list_azure_node_pools(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_azure_node_pools_async_pager(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_node_pools), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - ], - next_page_token='abc', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[], - next_page_token='def', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_azure_node_pools(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, azure_resources.AzureNodePool) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_azure_node_pools_async_pages(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_node_pools), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - ], - next_page_token='abc', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[], - next_page_token='def', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - ], - ), - 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_azure_node_pools(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", [ - azure_service.DeleteAzureNodePoolRequest, - dict, -]) -def test_delete_azure_node_pool(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.DeleteAzureNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_azure_node_pool_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.DeleteAzureNodePoolRequest( - name='name_value', - etag='etag_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_azure_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.DeleteAzureNodePoolRequest( - name='name_value', - etag='etag_value', - ) - -def test_delete_azure_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_azure_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_azure_node_pool] = mock_rpc - request = {} - client.delete_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_azure_node_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_azure_node_pool in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_azure_node_pool] = mock_rpc - - request = {} - await client.delete_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_azure_node_pool_async(transport: str = 'grpc_asyncio', request_type=azure_service.DeleteAzureNodePoolRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_node_pool), - '__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_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.DeleteAzureNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_azure_node_pool_async_from_dict(): - await test_delete_azure_node_pool_async(request_type=dict) - -def test_delete_azure_node_pool_field_headers(): - client = AzureClustersClient( - 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 = azure_service.DeleteAzureNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_azure_node_pool(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_azure_node_pool_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.DeleteAzureNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_azure_node_pool(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_azure_node_pool_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_node_pool), - '__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_azure_node_pool( - 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_azure_node_pool_flattened_error(): - client = AzureClustersClient( - 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_azure_node_pool( - azure_service.DeleteAzureNodePoolRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_azure_node_pool_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_node_pool), - '__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_azure_node_pool( - 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_azure_node_pool_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_azure_node_pool( - azure_service.DeleteAzureNodePoolRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureOpenIdConfigRequest, - dict, -]) -def test_get_azure_open_id_config(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_open_id_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureOpenIdConfig( - issuer='issuer_value', - jwks_uri='jwks_uri_value', - response_types_supported=['response_types_supported_value'], - subject_types_supported=['subject_types_supported_value'], - id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], - claims_supported=['claims_supported_value'], - grant_types=['grant_types_value'], - ) - response = client.get_azure_open_id_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureOpenIdConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureOpenIdConfig) - assert response.issuer == 'issuer_value' - assert response.jwks_uri == 'jwks_uri_value' - assert response.response_types_supported == ['response_types_supported_value'] - assert response.subject_types_supported == ['subject_types_supported_value'] - assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] - assert response.claims_supported == ['claims_supported_value'] - assert response.grant_types == ['grant_types_value'] - - -def test_get_azure_open_id_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.GetAzureOpenIdConfigRequest( - azure_cluster='azure_cluster_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_open_id_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_azure_open_id_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.GetAzureOpenIdConfigRequest( - azure_cluster='azure_cluster_value', - ) - -def test_get_azure_open_id_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_open_id_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_open_id_config] = mock_rpc - request = {} - client.get_azure_open_id_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_open_id_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_open_id_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_azure_open_id_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_azure_open_id_config] = mock_rpc - - request = {} - await client.get_azure_open_id_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_azure_open_id_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_open_id_config_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureOpenIdConfigRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_open_id_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureOpenIdConfig( - issuer='issuer_value', - jwks_uri='jwks_uri_value', - response_types_supported=['response_types_supported_value'], - subject_types_supported=['subject_types_supported_value'], - id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], - claims_supported=['claims_supported_value'], - grant_types=['grant_types_value'], - )) - response = await client.get_azure_open_id_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureOpenIdConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureOpenIdConfig) - assert response.issuer == 'issuer_value' - assert response.jwks_uri == 'jwks_uri_value' - assert response.response_types_supported == ['response_types_supported_value'] - assert response.subject_types_supported == ['subject_types_supported_value'] - assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] - assert response.claims_supported == ['claims_supported_value'] - assert response.grant_types == ['grant_types_value'] - - -@pytest.mark.asyncio -async def test_get_azure_open_id_config_async_from_dict(): - await test_get_azure_open_id_config_async(request_type=dict) - -def test_get_azure_open_id_config_field_headers(): - client = AzureClustersClient( - 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 = azure_service.GetAzureOpenIdConfigRequest() - - request.azure_cluster = 'azure_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_open_id_config), - '__call__') as call: - call.return_value = azure_resources.AzureOpenIdConfig() - client.get_azure_open_id_config(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', - 'azure_cluster=azure_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_azure_open_id_config_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.GetAzureOpenIdConfigRequest() - - request.azure_cluster = 'azure_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_open_id_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureOpenIdConfig()) - await client.get_azure_open_id_config(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', - 'azure_cluster=azure_cluster_value', - ) in kw['metadata'] - - -def test_get_azure_open_id_config_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_open_id_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureOpenIdConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_azure_open_id_config( - azure_cluster='azure_cluster_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].azure_cluster - mock_val = 'azure_cluster_value' - assert arg == mock_val - - -def test_get_azure_open_id_config_flattened_error(): - client = AzureClustersClient( - 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_azure_open_id_config( - azure_service.GetAzureOpenIdConfigRequest(), - azure_cluster='azure_cluster_value', - ) - -@pytest.mark.asyncio -async def test_get_azure_open_id_config_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_open_id_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureOpenIdConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureOpenIdConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_azure_open_id_config( - azure_cluster='azure_cluster_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].azure_cluster - mock_val = 'azure_cluster_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_azure_open_id_config_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_azure_open_id_config( - azure_service.GetAzureOpenIdConfigRequest(), - azure_cluster='azure_cluster_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureJsonWebKeysRequest, - dict, -]) -def test_get_azure_json_web_keys(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_json_web_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureJsonWebKeys( - ) - response = client.get_azure_json_web_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureJsonWebKeysRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureJsonWebKeys) - - -def test_get_azure_json_web_keys_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.GetAzureJsonWebKeysRequest( - azure_cluster='azure_cluster_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_json_web_keys), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_azure_json_web_keys(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.GetAzureJsonWebKeysRequest( - azure_cluster='azure_cluster_value', - ) - -def test_get_azure_json_web_keys_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_json_web_keys in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_json_web_keys] = mock_rpc - request = {} - client.get_azure_json_web_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_json_web_keys(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_json_web_keys_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_azure_json_web_keys in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_azure_json_web_keys] = mock_rpc - - request = {} - await client.get_azure_json_web_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_azure_json_web_keys(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_json_web_keys_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureJsonWebKeysRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_json_web_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureJsonWebKeys( - )) - response = await client.get_azure_json_web_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureJsonWebKeysRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureJsonWebKeys) - - -@pytest.mark.asyncio -async def test_get_azure_json_web_keys_async_from_dict(): - await test_get_azure_json_web_keys_async(request_type=dict) - -def test_get_azure_json_web_keys_field_headers(): - client = AzureClustersClient( - 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 = azure_service.GetAzureJsonWebKeysRequest() - - request.azure_cluster = 'azure_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_json_web_keys), - '__call__') as call: - call.return_value = azure_resources.AzureJsonWebKeys() - client.get_azure_json_web_keys(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', - 'azure_cluster=azure_cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_azure_json_web_keys_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.GetAzureJsonWebKeysRequest() - - request.azure_cluster = 'azure_cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_json_web_keys), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureJsonWebKeys()) - await client.get_azure_json_web_keys(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', - 'azure_cluster=azure_cluster_value', - ) in kw['metadata'] - - -def test_get_azure_json_web_keys_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_json_web_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureJsonWebKeys() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_azure_json_web_keys( - azure_cluster='azure_cluster_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].azure_cluster - mock_val = 'azure_cluster_value' - assert arg == mock_val - - -def test_get_azure_json_web_keys_flattened_error(): - client = AzureClustersClient( - 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_azure_json_web_keys( - azure_service.GetAzureJsonWebKeysRequest(), - azure_cluster='azure_cluster_value', - ) - -@pytest.mark.asyncio -async def test_get_azure_json_web_keys_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_json_web_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureJsonWebKeys() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureJsonWebKeys()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_azure_json_web_keys( - azure_cluster='azure_cluster_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].azure_cluster - mock_val = 'azure_cluster_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_azure_json_web_keys_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_azure_json_web_keys( - azure_service.GetAzureJsonWebKeysRequest(), - azure_cluster='azure_cluster_value', - ) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureServerConfigRequest, - dict, -]) -def test_get_azure_server_config(request_type, transport: str = 'grpc'): - client = AzureClustersClient( - 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_azure_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureServerConfig( - name='name_value', - supported_azure_regions=['supported_azure_regions_value'], - ) - response = client.get_azure_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureServerConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureServerConfig) - assert response.name == 'name_value' - assert response.supported_azure_regions == ['supported_azure_regions_value'] - - -def test_get_azure_server_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = azure_service.GetAzureServerConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_server_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_azure_server_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == azure_service.GetAzureServerConfigRequest( - name='name_value', - ) - -def test_get_azure_server_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_server_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_server_config] = mock_rpc - request = {} - client.get_azure_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_server_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_server_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_azure_server_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_azure_server_config] = mock_rpc - - request = {} - await client.get_azure_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_azure_server_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_azure_server_config_async(transport: str = 'grpc_asyncio', request_type=azure_service.GetAzureServerConfigRequest): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_azure_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureServerConfig( - name='name_value', - supported_azure_regions=['supported_azure_regions_value'], - )) - response = await client.get_azure_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = azure_service.GetAzureServerConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureServerConfig) - assert response.name == 'name_value' - assert response.supported_azure_regions == ['supported_azure_regions_value'] - - -@pytest.mark.asyncio -async def test_get_azure_server_config_async_from_dict(): - await test_get_azure_server_config_async(request_type=dict) - -def test_get_azure_server_config_field_headers(): - client = AzureClustersClient( - 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 = azure_service.GetAzureServerConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_server_config), - '__call__') as call: - call.return_value = azure_resources.AzureServerConfig() - client.get_azure_server_config(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_azure_server_config_field_headers_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = azure_service.GetAzureServerConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_server_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureServerConfig()) - await client.get_azure_server_config(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_azure_server_config_flattened(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureServerConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_azure_server_config( - 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_azure_server_config_flattened_error(): - client = AzureClustersClient( - 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_azure_server_config( - azure_service.GetAzureServerConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_azure_server_config_flattened_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = azure_resources.AzureServerConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureServerConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_azure_server_config( - 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_azure_server_config_flattened_error_async(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_azure_server_config( - azure_service.GetAzureServerConfigRequest(), - name='name_value', - ) - - -def test_create_azure_client_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_azure_client in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_azure_client] = mock_rpc - - request = {} - client.create_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_azure_client(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_azure_client_rest_required_fields(request_type=azure_service.CreateAzureClientRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["azure_client_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "azureClientId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_client._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "azureClientId" in jsonified_request - assert jsonified_request["azureClientId"] == request_init["azure_client_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["azureClientId"] = 'azure_client_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_client._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("azure_client_id", "validate_only", )) - 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 "azureClientId" in jsonified_request - assert jsonified_request["azureClientId"] == 'azure_client_id_value' - - client = AzureClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_azure_client(request) - - expected_params = [ - ( - "azureClientId", - "", - ), - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_azure_client_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_azure_client._get_unset_required_fields({}) - assert set(unset_fields) == (set(("azureClientId", "validateOnly", )) & set(("parent", "azureClient", "azureClientId", ))) - - -def test_create_azure_client_rest_flattened(): - client = AzureClustersClient( - 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', - azure_client=azure_resources.AzureClient(name='name_value'), - azure_client_id='azure_client_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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_azure_client(**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/*}/azureClients" % client.transport._host, args[1]) - - -def test_create_azure_client_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_client( - azure_service.CreateAzureClientRequest(), - parent='parent_value', - azure_client=azure_resources.AzureClient(name='name_value'), - azure_client_id='azure_client_id_value', - ) - - -def test_get_azure_client_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_client in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_client] = mock_rpc - - request = {} - client.get_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_client(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_azure_client_rest_required_fields(request_type=azure_service.GetAzureClientRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_client._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_azure_client._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 = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_resources.AzureClient() - # 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 = azure_resources.AzureClient.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_azure_client(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_azure_client_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_azure_client._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_azure_client_rest_flattened(): - client = AzureClustersClient( - 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 = azure_resources.AzureClient() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/azureClients/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 = azure_resources.AzureClient.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_azure_client(**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/*/azureClients/*}" % client.transport._host, args[1]) - - -def test_get_azure_client_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_client( - azure_service.GetAzureClientRequest(), - name='name_value', - ) - - -def test_list_azure_clients_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_azure_clients in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_azure_clients] = mock_rpc - - request = {} - client.list_azure_clients(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_azure_clients(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_azure_clients_rest_required_fields(request_type=azure_service.ListAzureClientsRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_azure_clients._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_azure_clients._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - 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 = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_service.ListAzureClientsResponse() - # 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 = azure_service.ListAzureClientsResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_azure_clients(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_azure_clients_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_azure_clients._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_azure_clients_rest_flattened(): - client = AzureClustersClient( - 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 = azure_service.ListAzureClientsResponse() - - # 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 = azure_service.ListAzureClientsResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_azure_clients(**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/*}/azureClients" % client.transport._host, args[1]) - - -def test_list_azure_clients_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_clients( - azure_service.ListAzureClientsRequest(), - parent='parent_value', - ) - - -def test_list_azure_clients_rest_pager(transport: str = 'rest'): - client = AzureClustersClient( - 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 = ( - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - azure_resources.AzureClient(), - azure_resources.AzureClient(), - ], - next_page_token='abc', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[], - next_page_token='def', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureClientsResponse( - azure_clients=[ - azure_resources.AzureClient(), - azure_resources.AzureClient(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(azure_service.ListAzureClientsResponse.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_azure_clients(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, azure_resources.AzureClient) - for i in results) - - pages = list(client.list_azure_clients(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_azure_client_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_azure_client in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_azure_client] = mock_rpc - - request = {} - client.delete_azure_client(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_azure_client(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_azure_client_rest_required_fields(request_type=azure_service.DeleteAzureClientRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_azure_client._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_azure_client._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = AzureClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_azure_client(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_azure_client_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_azure_client._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "validateOnly", )) & set(("name", ))) - - -def test_delete_azure_client_rest_flattened(): - client = AzureClustersClient( - 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/azureClients/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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_azure_client(**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/*/azureClients/*}" % client.transport._host, args[1]) - - -def test_delete_azure_client_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_client( - azure_service.DeleteAzureClientRequest(), - name='name_value', - ) - - -def test_create_azure_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_azure_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_azure_cluster] = mock_rpc - - request = {} - client.create_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_azure_cluster_rest_required_fields(request_type=azure_service.CreateAzureClusterRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["azure_cluster_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "azureClusterId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "azureClusterId" in jsonified_request - assert jsonified_request["azureClusterId"] == request_init["azure_cluster_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["azureClusterId"] = 'azure_cluster_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("azure_cluster_id", "validate_only", )) - 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 "azureClusterId" in jsonified_request - assert jsonified_request["azureClusterId"] == 'azure_cluster_id_value' - - client = AzureClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_azure_cluster(request) - - expected_params = [ - ( - "azureClusterId", - "", - ), - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_azure_cluster_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_azure_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("azureClusterId", "validateOnly", )) & set(("parent", "azureCluster", "azureClusterId", ))) - - -def test_create_azure_cluster_rest_flattened(): - client = AzureClustersClient( - 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', - azure_cluster=azure_resources.AzureCluster(name='name_value'), - azure_cluster_id='azure_cluster_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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_azure_cluster(**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/*}/azureClusters" % client.transport._host, args[1]) - - -def test_create_azure_cluster_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_cluster( - azure_service.CreateAzureClusterRequest(), - parent='parent_value', - azure_cluster=azure_resources.AzureCluster(name='name_value'), - azure_cluster_id='azure_cluster_id_value', - ) - - -def test_update_azure_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_azure_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_azure_cluster] = mock_rpc - - request = {} - client.update_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_azure_cluster_rest_required_fields(request_type=azure_service.UpdateAzureClusterRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_azure_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_azure_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AzureClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_azure_cluster(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_azure_cluster_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_azure_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("azureCluster", "updateMask", ))) - - -def test_update_azure_cluster_rest_flattened(): - client = AzureClustersClient( - 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 = {'azure_cluster': {'name': 'projects/sample1/locations/sample2/azureClusters/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - azure_cluster=azure_resources.AzureCluster(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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_azure_cluster(**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/{azure_cluster.name=projects/*/locations/*/azureClusters/*}" % client.transport._host, args[1]) - - -def test_update_azure_cluster_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_cluster( - azure_service.UpdateAzureClusterRequest(), - azure_cluster=azure_resources.AzureCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_azure_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_cluster] = mock_rpc - - request = {} - client.get_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_azure_cluster_rest_required_fields(request_type=azure_service.GetAzureClusterRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_cluster._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_azure_cluster._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 = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_resources.AzureCluster() - # 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 = azure_resources.AzureCluster.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_azure_cluster(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_azure_cluster_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_azure_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_azure_cluster_rest_flattened(): - client = AzureClustersClient( - 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 = azure_resources.AzureCluster() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/azureClusters/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 = azure_resources.AzureCluster.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_azure_cluster(**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/*/azureClusters/*}" % client.transport._host, args[1]) - - -def test_get_azure_cluster_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_cluster( - azure_service.GetAzureClusterRequest(), - name='name_value', - ) - - -def test_list_azure_clusters_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_azure_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_azure_clusters] = mock_rpc - - request = {} - client.list_azure_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_azure_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_azure_clusters_rest_required_fields(request_type=azure_service.ListAzureClustersRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_azure_clusters._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_azure_clusters._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - 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 = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_service.ListAzureClustersResponse() - # 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 = azure_service.ListAzureClustersResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_azure_clusters(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_azure_clusters_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_azure_clusters._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_azure_clusters_rest_flattened(): - client = AzureClustersClient( - 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 = azure_service.ListAzureClustersResponse() - - # 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 = azure_service.ListAzureClustersResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_azure_clusters(**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/*}/azureClusters" % client.transport._host, args[1]) - - -def test_list_azure_clusters_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_clusters( - azure_service.ListAzureClustersRequest(), - parent='parent_value', - ) - - -def test_list_azure_clusters_rest_pager(transport: str = 'rest'): - client = AzureClustersClient( - 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 = ( - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - ], - next_page_token='abc', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[], - next_page_token='def', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureClustersResponse( - azure_clusters=[ - azure_resources.AzureCluster(), - azure_resources.AzureCluster(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(azure_service.ListAzureClustersResponse.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_azure_clusters(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, azure_resources.AzureCluster) - for i in results) - - pages = list(client.list_azure_clusters(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_azure_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_azure_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_azure_cluster] = mock_rpc - - request = {} - client.delete_azure_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_azure_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_azure_cluster_rest_required_fields(request_type=azure_service.DeleteAzureClusterRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_azure_cluster._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_azure_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "etag", "ignore_errors", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = AzureClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_azure_cluster(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_azure_cluster_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_azure_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "etag", "ignoreErrors", "validateOnly", )) & set(("name", ))) - - -def test_delete_azure_cluster_rest_flattened(): - client = AzureClustersClient( - 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/azureClusters/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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_azure_cluster(**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/*/azureClusters/*}" % client.transport._host, args[1]) - - -def test_delete_azure_cluster_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_cluster( - azure_service.DeleteAzureClusterRequest(), - name='name_value', - ) - - -def test_generate_azure_cluster_agent_token_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_azure_cluster_agent_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_azure_cluster_agent_token] = mock_rpc - - request = {} - client.generate_azure_cluster_agent_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_azure_cluster_agent_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_azure_cluster_agent_token_rest_required_fields(request_type=azure_service.GenerateAzureClusterAgentTokenRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["azure_cluster"] = "" - request_init["subject_token"] = "" - request_init["subject_token_type"] = "" - request_init["version"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_azure_cluster_agent_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["azureCluster"] = 'azure_cluster_value' - jsonified_request["subjectToken"] = 'subject_token_value' - jsonified_request["subjectTokenType"] = 'subject_token_type_value' - jsonified_request["version"] = 'version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_azure_cluster_agent_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "azureCluster" in jsonified_request - assert jsonified_request["azureCluster"] == 'azure_cluster_value' - assert "subjectToken" in jsonified_request - assert jsonified_request["subjectToken"] == 'subject_token_value' - assert "subjectTokenType" in jsonified_request - assert jsonified_request["subjectTokenType"] == 'subject_token_type_value' - assert "version" in jsonified_request - assert jsonified_request["version"] == 'version_value' - - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_service.GenerateAzureClusterAgentTokenResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_service.GenerateAzureClusterAgentTokenResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.generate_azure_cluster_agent_token(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_azure_cluster_agent_token_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_azure_cluster_agent_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("azureCluster", "subjectToken", "subjectTokenType", "version", ))) - - -def test_generate_azure_access_token_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_azure_access_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_azure_access_token] = mock_rpc - - request = {} - client.generate_azure_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_azure_access_token(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_azure_access_token_rest_required_fields(request_type=azure_service.GenerateAzureAccessTokenRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["azure_cluster"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_azure_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["azureCluster"] = 'azure_cluster_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_azure_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "azureCluster" in jsonified_request - assert jsonified_request["azureCluster"] == 'azure_cluster_value' - - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_service.GenerateAzureAccessTokenResponse() - # 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 = azure_service.GenerateAzureAccessTokenResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.generate_azure_access_token(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_azure_access_token_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_azure_access_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("azureCluster", ))) - - -def test_create_azure_node_pool_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_azure_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_azure_node_pool] = mock_rpc - - request = {} - client.create_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_azure_node_pool_rest_required_fields(request_type=azure_service.CreateAzureNodePoolRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["azure_node_pool_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "azureNodePoolId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_node_pool._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "azureNodePoolId" in jsonified_request - assert jsonified_request["azureNodePoolId"] == request_init["azure_node_pool_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["azureNodePoolId"] = 'azure_node_pool_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_azure_node_pool._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("azure_node_pool_id", "validate_only", )) - 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 "azureNodePoolId" in jsonified_request - assert jsonified_request["azureNodePoolId"] == 'azure_node_pool_id_value' - - client = AzureClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_azure_node_pool(request) - - expected_params = [ - ( - "azureNodePoolId", - "", - ), - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_azure_node_pool_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_azure_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(("azureNodePoolId", "validateOnly", )) & set(("parent", "azureNodePool", "azureNodePoolId", ))) - - -def test_create_azure_node_pool_rest_flattened(): - client = AzureClustersClient( - 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/azureClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - azure_node_pool=azure_resources.AzureNodePool(name='name_value'), - azure_node_pool_id='azure_node_pool_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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_azure_node_pool(**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/*/azureClusters/*}/azureNodePools" % client.transport._host, args[1]) - - -def test_create_azure_node_pool_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_node_pool( - azure_service.CreateAzureNodePoolRequest(), - parent='parent_value', - azure_node_pool=azure_resources.AzureNodePool(name='name_value'), - azure_node_pool_id='azure_node_pool_id_value', - ) - - -def test_update_azure_node_pool_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_azure_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_azure_node_pool] = mock_rpc - - request = {} - client.update_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_azure_node_pool_rest_required_fields(request_type=azure_service.UpdateAzureNodePoolRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_azure_node_pool._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_azure_node_pool._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AzureClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_azure_node_pool(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_azure_node_pool_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_azure_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("azureNodePool", "updateMask", ))) - - -def test_update_azure_node_pool_rest_flattened(): - client = AzureClustersClient( - 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 = {'azure_node_pool': {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - azure_node_pool=azure_resources.AzureNodePool(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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_azure_node_pool(**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/{azure_node_pool.name=projects/*/locations/*/azureClusters/*/azureNodePools/*}" % client.transport._host, args[1]) - - -def test_update_azure_node_pool_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_node_pool( - azure_service.UpdateAzureNodePoolRequest(), - azure_node_pool=azure_resources.AzureNodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_azure_node_pool_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_node_pool] = mock_rpc - - request = {} - client.get_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_azure_node_pool_rest_required_fields(request_type=azure_service.GetAzureNodePoolRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_node_pool._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_azure_node_pool._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 = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_resources.AzureNodePool() - # 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 = azure_resources.AzureNodePool.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_azure_node_pool(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_azure_node_pool_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_azure_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_azure_node_pool_rest_flattened(): - client = AzureClustersClient( - 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 = azure_resources.AzureNodePool() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = azure_resources.AzureNodePool.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_azure_node_pool(**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/*/azureClusters/*/azureNodePools/*}" % client.transport._host, args[1]) - - -def test_get_azure_node_pool_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_node_pool( - azure_service.GetAzureNodePoolRequest(), - name='name_value', - ) - - -def test_list_azure_node_pools_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_azure_node_pools in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_azure_node_pools] = mock_rpc - - request = {} - client.list_azure_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_azure_node_pools(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_azure_node_pools_rest_required_fields(request_type=azure_service.ListAzureNodePoolsRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_azure_node_pools._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_azure_node_pools._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - 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 = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_service.ListAzureNodePoolsResponse() - # 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 = azure_service.ListAzureNodePoolsResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_azure_node_pools(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_azure_node_pools_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_azure_node_pools._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_azure_node_pools_rest_flattened(): - client = AzureClustersClient( - 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 = azure_service.ListAzureNodePoolsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/azureClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = azure_service.ListAzureNodePoolsResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_azure_node_pools(**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/*/azureClusters/*}/azureNodePools" % client.transport._host, args[1]) - - -def test_list_azure_node_pools_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_node_pools( - azure_service.ListAzureNodePoolsRequest(), - parent='parent_value', - ) - - -def test_list_azure_node_pools_rest_pager(transport: str = 'rest'): - client = AzureClustersClient( - 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 = ( - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - ], - next_page_token='abc', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[], - next_page_token='def', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - ], - next_page_token='ghi', - ), - azure_service.ListAzureNodePoolsResponse( - azure_node_pools=[ - azure_resources.AzureNodePool(), - azure_resources.AzureNodePool(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(azure_service.ListAzureNodePoolsResponse.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/azureClusters/sample3'} - - pager = client.list_azure_node_pools(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, azure_resources.AzureNodePool) - for i in results) - - pages = list(client.list_azure_node_pools(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_azure_node_pool_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_azure_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_azure_node_pool] = mock_rpc - - request = {} - client.delete_azure_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_azure_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_azure_node_pool_rest_required_fields(request_type=azure_service.DeleteAzureNodePoolRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_azure_node_pool._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_azure_node_pool._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "etag", "ignore_errors", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = AzureClustersClient( - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_azure_node_pool(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_azure_node_pool_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_azure_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "etag", "ignoreErrors", "validateOnly", )) & set(("name", ))) - - -def test_delete_azure_node_pool_rest_flattened(): - client = AzureClustersClient( - 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/azureClusters/sample3/azureNodePools/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_azure_node_pool(**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/*/azureClusters/*/azureNodePools/*}" % client.transport._host, args[1]) - - -def test_delete_azure_node_pool_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_node_pool( - azure_service.DeleteAzureNodePoolRequest(), - name='name_value', - ) - - -def test_get_azure_open_id_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_open_id_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_open_id_config] = mock_rpc - - request = {} - client.get_azure_open_id_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_open_id_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_azure_open_id_config_rest_required_fields(request_type=azure_service.GetAzureOpenIdConfigRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["azure_cluster"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_open_id_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["azureCluster"] = 'azure_cluster_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_open_id_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "azureCluster" in jsonified_request - assert jsonified_request["azureCluster"] == 'azure_cluster_value' - - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_resources.AzureOpenIdConfig() - # 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 = azure_resources.AzureOpenIdConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_azure_open_id_config(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_azure_open_id_config_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_azure_open_id_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("azureCluster", ))) - - -def test_get_azure_open_id_config_rest_flattened(): - client = AzureClustersClient( - 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 = azure_resources.AzureOpenIdConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - azure_cluster='azure_cluster_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 = azure_resources.AzureOpenIdConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_azure_open_id_config(**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/{azure_cluster=projects/*/locations/*/azureClusters/*}/.well-known/openid-configuration" % client.transport._host, args[1]) - - -def test_get_azure_open_id_config_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_open_id_config( - azure_service.GetAzureOpenIdConfigRequest(), - azure_cluster='azure_cluster_value', - ) - - -def test_get_azure_json_web_keys_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_json_web_keys in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_json_web_keys] = mock_rpc - - request = {} - client.get_azure_json_web_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_json_web_keys(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_azure_json_web_keys_rest_required_fields(request_type=azure_service.GetAzureJsonWebKeysRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["azure_cluster"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_json_web_keys._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["azureCluster"] = 'azure_cluster_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_json_web_keys._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "azureCluster" in jsonified_request - assert jsonified_request["azureCluster"] == 'azure_cluster_value' - - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_resources.AzureJsonWebKeys() - # 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 = azure_resources.AzureJsonWebKeys.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_azure_json_web_keys(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_azure_json_web_keys_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_azure_json_web_keys._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("azureCluster", ))) - - -def test_get_azure_json_web_keys_rest_flattened(): - client = AzureClustersClient( - 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 = azure_resources.AzureJsonWebKeys() - - # get arguments that satisfy an http rule for this method - sample_request = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - azure_cluster='azure_cluster_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 = azure_resources.AzureJsonWebKeys.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_azure_json_web_keys(**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/{azure_cluster=projects/*/locations/*/azureClusters/*}/jwks" % client.transport._host, args[1]) - - -def test_get_azure_json_web_keys_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_json_web_keys( - azure_service.GetAzureJsonWebKeysRequest(), - azure_cluster='azure_cluster_value', - ) - - -def test_get_azure_server_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_azure_server_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_azure_server_config] = mock_rpc - - request = {} - client.get_azure_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_azure_server_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_azure_server_config_rest_required_fields(request_type=azure_service.GetAzureServerConfigRequest): - transport_class = transports.AzureClustersRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_azure_server_config._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_azure_server_config._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 = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = azure_resources.AzureServerConfig() - # 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 = azure_resources.AzureServerConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_azure_server_config(request) - - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_azure_server_config_rest_unset_required_fields(): - transport = transports.AzureClustersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_azure_server_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_azure_server_config_rest_flattened(): - client = AzureClustersClient( - 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 = azure_resources.AzureServerConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/azureServerConfig'} - - # 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 = azure_resources.AzureServerConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_azure_server_config(**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/*/azureServerConfig}" % client.transport._host, args[1]) - - -def test_get_azure_server_config_rest_flattened_error(transport: str = 'rest'): - client = AzureClustersClient( - 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_azure_server_config( - azure_service.GetAzureServerConfigRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AzureClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AzureClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AzureClustersClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AzureClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AzureClustersClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AzureClustersClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AzureClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AzureClustersClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AzureClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AzureClustersClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AzureClustersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AzureClustersGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AzureClustersGrpcTransport, - transports.AzureClustersGrpcAsyncIOTransport, - transports.AzureClustersRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = AzureClustersClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_azure_client_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_client), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_azure_client(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.CreateAzureClientRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_client_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_client), - '__call__') as call: - call.return_value = azure_resources.AzureClient() - client.get_azure_client(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureClientRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_azure_clients_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clients), - '__call__') as call: - call.return_value = azure_service.ListAzureClientsResponse() - client.list_azure_clients(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.ListAzureClientsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_azure_client_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_client), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_azure_client(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.DeleteAzureClientRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_azure_cluster_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.CreateAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_azure_cluster_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.UpdateAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_cluster_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_cluster), - '__call__') as call: - call.return_value = azure_resources.AzureCluster() - client.get_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_azure_clusters_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clusters), - '__call__') as call: - call.return_value = azure_service.ListAzureClustersResponse() - client.list_azure_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.ListAzureClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_azure_cluster_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.DeleteAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_azure_cluster_agent_token_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_cluster_agent_token), - '__call__') as call: - call.return_value = azure_service.GenerateAzureClusterAgentTokenResponse() - client.generate_azure_cluster_agent_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GenerateAzureClusterAgentTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_azure_access_token_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_access_token), - '__call__') as call: - call.return_value = azure_service.GenerateAzureAccessTokenResponse() - client.generate_azure_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GenerateAzureAccessTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_azure_node_pool_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.CreateAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_azure_node_pool_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.UpdateAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_node_pool_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_node_pool), - '__call__') as call: - call.return_value = azure_resources.AzureNodePool() - client.get_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_azure_node_pools_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_node_pools), - '__call__') as call: - call.return_value = azure_service.ListAzureNodePoolsResponse() - client.list_azure_node_pools(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.ListAzureNodePoolsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_azure_node_pool_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.DeleteAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_open_id_config_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_open_id_config), - '__call__') as call: - call.return_value = azure_resources.AzureOpenIdConfig() - client.get_azure_open_id_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureOpenIdConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_json_web_keys_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_json_web_keys), - '__call__') as call: - call.return_value = azure_resources.AzureJsonWebKeys() - client.get_azure_json_web_keys(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureJsonWebKeysRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_server_config_empty_call_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_server_config), - '__call__') as call: - call.return_value = azure_resources.AzureServerConfig() - client.get_azure_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureServerConfigRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AzureClustersAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_azure_client_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_client), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_azure_client(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.CreateAzureClientRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_azure_client_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_client), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureClient( - name='name_value', - tenant_id='tenant_id_value', - application_id='application_id_value', - reconciling=True, - pem_certificate='pem_certificate_value', - uid='uid_value', - )) - await client.get_azure_client(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureClientRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_azure_clients_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clients), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClientsResponse( - next_page_token='next_page_token_value', - )) - await client.list_azure_clients(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.ListAzureClientsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_azure_client_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_client), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_azure_client(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.DeleteAzureClientRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_azure_cluster_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.CreateAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_azure_cluster_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.UpdateAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_azure_cluster_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureCluster( - name='name_value', - description='description_value', - azure_region='azure_region_value', - resource_group_id='resource_group_id_value', - azure_client='azure_client_value', - state=azure_resources.AzureCluster.State.PROVISIONING, - endpoint='endpoint_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - cluster_ca_certificate='cluster_ca_certificate_value', - )) - await client.get_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_azure_clusters_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureClustersResponse( - next_page_token='next_page_token_value', - )) - await client.list_azure_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.ListAzureClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_azure_cluster_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.DeleteAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_azure_cluster_agent_token_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_cluster_agent_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - )) - await client.generate_azure_cluster_agent_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GenerateAzureClusterAgentTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_azure_access_token_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.GenerateAzureAccessTokenResponse( - access_token='access_token_value', - )) - await client.generate_azure_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GenerateAzureAccessTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_azure_node_pool_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.CreateAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_azure_node_pool_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.UpdateAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_azure_node_pool_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureNodePool( - name='name_value', - version='version_value', - subnet_id='subnet_id_value', - state=azure_resources.AzureNodePool.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - azure_availability_zone='azure_availability_zone_value', - )) - await client.get_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_azure_node_pools_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_service.ListAzureNodePoolsResponse( - next_page_token='next_page_token_value', - )) - await client.list_azure_node_pools(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.ListAzureNodePoolsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_azure_node_pool_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.DeleteAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_azure_open_id_config_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_open_id_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureOpenIdConfig( - issuer='issuer_value', - jwks_uri='jwks_uri_value', - response_types_supported=['response_types_supported_value'], - subject_types_supported=['subject_types_supported_value'], - id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], - claims_supported=['claims_supported_value'], - grant_types=['grant_types_value'], - )) - await client.get_azure_open_id_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureOpenIdConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_azure_json_web_keys_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_json_web_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureJsonWebKeys( - )) - await client.get_azure_json_web_keys(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureJsonWebKeysRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_azure_server_config_empty_call_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(azure_resources.AzureServerConfig( - name='name_value', - supported_azure_regions=['supported_azure_regions_value'], - )) - await client.get_azure_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureServerConfigRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AzureClustersClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_azure_client_rest_bad_request(request_type=azure_service.CreateAzureClientRequest): - client = AzureClustersClient( - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_azure_client(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.CreateAzureClientRequest, - dict, -]) -def test_create_azure_client_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["azure_client"] = {'name': 'name_value', 'tenant_id': 'tenant_id_value', 'application_id': 'application_id_value', 'reconciling': True, 'annotations': {}, 'pem_certificate': 'pem_certificate_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_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 = azure_service.CreateAzureClientRequest.meta.fields["azure_client"] - - 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["azure_client"].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["azure_client"][field])): - del request_init["azure_client"][field][i][subfield] - else: - del request_init["azure_client"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_azure_client(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_azure_client_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_create_azure_client") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_create_azure_client") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.CreateAzureClientRequest.pb(azure_service.CreateAzureClientRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = azure_service.CreateAzureClientRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_azure_client(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_azure_client_rest_bad_request(request_type=azure_service.GetAzureClientRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClients/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_azure_client(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureClientRequest, - dict, -]) -def test_get_azure_client_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClients/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 = azure_resources.AzureClient( - name='name_value', - tenant_id='tenant_id_value', - application_id='application_id_value', - reconciling=True, - pem_certificate='pem_certificate_value', - uid='uid_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_resources.AzureClient.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_azure_client(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureClient) - assert response.name == 'name_value' - assert response.tenant_id == 'tenant_id_value' - assert response.application_id == 'application_id_value' - assert response.reconciling is True - assert response.pem_certificate == 'pem_certificate_value' - assert response.uid == 'uid_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_azure_client_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_client") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_client") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.GetAzureClientRequest.pb(azure_service.GetAzureClientRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_resources.AzureClient.to_json(azure_resources.AzureClient()) - req.return_value.content = return_value - - request = azure_service.GetAzureClientRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_resources.AzureClient() - - client.get_azure_client(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_azure_clients_rest_bad_request(request_type=azure_service.ListAzureClientsRequest): - client = AzureClustersClient( - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_azure_clients(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.ListAzureClientsRequest, - dict, -]) -def test_list_azure_clients_rest_call_success(request_type): - client = AzureClustersClient( - 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 = azure_service.ListAzureClientsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_service.ListAzureClientsResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_azure_clients(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAzureClientsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_azure_clients_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_list_azure_clients") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_list_azure_clients") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.ListAzureClientsRequest.pb(azure_service.ListAzureClientsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_service.ListAzureClientsResponse.to_json(azure_service.ListAzureClientsResponse()) - req.return_value.content = return_value - - request = azure_service.ListAzureClientsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_service.ListAzureClientsResponse() - - client.list_azure_clients(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_azure_client_rest_bad_request(request_type=azure_service.DeleteAzureClientRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClients/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_azure_client(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.DeleteAzureClientRequest, - dict, -]) -def test_delete_azure_client_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClients/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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_azure_client(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_azure_client_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_delete_azure_client") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_delete_azure_client") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.DeleteAzureClientRequest.pb(azure_service.DeleteAzureClientRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = azure_service.DeleteAzureClientRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_azure_client(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_azure_cluster_rest_bad_request(request_type=azure_service.CreateAzureClusterRequest): - client = AzureClustersClient( - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_azure_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.CreateAzureClusterRequest, - dict, -]) -def test_create_azure_cluster_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["azure_cluster"] = {'name': 'name_value', 'description': 'description_value', 'azure_region': 'azure_region_value', 'resource_group_id': 'resource_group_id_value', 'azure_client': 'azure_client_value', 'networking': {'virtual_network_id': 'virtual_network_id_value', 'pod_address_cidr_blocks': ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'], 'service_address_cidr_blocks': ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'], 'service_load_balancer_subnet_id': 'service_load_balancer_subnet_id_value'}, 'control_plane': {'version': 'version_value', 'subnet_id': 'subnet_id_value', 'vm_size': 'vm_size_value', 'ssh_config': {'authorized_key': 'authorized_key_value'}, 'root_volume': {'size_gib': 844}, 'main_volume': {}, 'database_encryption': {'key_id': 'key_id_value'}, 'proxy_config': {'resource_group_id': 'resource_group_id_value', 'secret_id': 'secret_id_value'}, 'config_encryption': {'key_id': 'key_id_value', 'public_key': 'public_key_value'}, 'tags': {}, 'replica_placements': [{'subnet_id': 'subnet_id_value', 'azure_availability_zone': 'azure_availability_zone_value'}], 'endpoint_subnet_id': 'endpoint_subnet_id_value'}, 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'azure_services_authentication': {'tenant_id': 'tenant_id_value', 'application_id': 'application_id_value'}, 'state': 1, 'endpoint': 'endpoint_value', 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'cluster_ca_certificate': 'cluster_ca_certificate_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'managed_resources': {'network_security_group_id': 'network_security_group_id_value', 'control_plane_application_security_group_id': 'control_plane_application_security_group_id_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}} - # 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 = azure_service.CreateAzureClusterRequest.meta.fields["azure_cluster"] - - 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["azure_cluster"].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["azure_cluster"][field])): - del request_init["azure_cluster"][field][i][subfield] - else: - del request_init["azure_cluster"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_azure_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_azure_cluster_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_create_azure_cluster") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_create_azure_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.CreateAzureClusterRequest.pb(azure_service.CreateAzureClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = azure_service.CreateAzureClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_azure_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_azure_cluster_rest_bad_request(request_type=azure_service.UpdateAzureClusterRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'azure_cluster': {'name': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_azure_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.UpdateAzureClusterRequest, - dict, -]) -def test_update_azure_cluster_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'azure_cluster': {'name': 'projects/sample1/locations/sample2/azureClusters/sample3'}} - request_init["azure_cluster"] = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3', 'description': 'description_value', 'azure_region': 'azure_region_value', 'resource_group_id': 'resource_group_id_value', 'azure_client': 'azure_client_value', 'networking': {'virtual_network_id': 'virtual_network_id_value', 'pod_address_cidr_blocks': ['pod_address_cidr_blocks_value1', 'pod_address_cidr_blocks_value2'], 'service_address_cidr_blocks': ['service_address_cidr_blocks_value1', 'service_address_cidr_blocks_value2'], 'service_load_balancer_subnet_id': 'service_load_balancer_subnet_id_value'}, 'control_plane': {'version': 'version_value', 'subnet_id': 'subnet_id_value', 'vm_size': 'vm_size_value', 'ssh_config': {'authorized_key': 'authorized_key_value'}, 'root_volume': {'size_gib': 844}, 'main_volume': {}, 'database_encryption': {'key_id': 'key_id_value'}, 'proxy_config': {'resource_group_id': 'resource_group_id_value', 'secret_id': 'secret_id_value'}, 'config_encryption': {'key_id': 'key_id_value', 'public_key': 'public_key_value'}, 'tags': {}, 'replica_placements': [{'subnet_id': 'subnet_id_value', 'azure_availability_zone': 'azure_availability_zone_value'}], 'endpoint_subnet_id': 'endpoint_subnet_id_value'}, 'authorization': {'admin_users': [{'username': 'username_value'}], 'admin_groups': [{'group': 'group_value'}]}, 'azure_services_authentication': {'tenant_id': 'tenant_id_value', 'application_id': 'application_id_value'}, 'state': 1, 'endpoint': 'endpoint_value', 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'workload_identity_config': {'issuer_uri': 'issuer_uri_value', 'workload_pool': 'workload_pool_value', 'identity_provider': 'identity_provider_value'}, 'cluster_ca_certificate': 'cluster_ca_certificate_value', 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'managed_resources': {'network_security_group_id': 'network_security_group_id_value', 'control_plane_application_security_group_id': 'control_plane_application_security_group_id_value'}, 'logging_config': {'component_config': {'enable_components': [1]}}, 'errors': [{'message': 'message_value'}], 'monitoring_config': {'managed_prometheus_config': {'enabled': True}, 'cloud_monitoring_config': {'enabled': True}}} - # 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 = azure_service.UpdateAzureClusterRequest.meta.fields["azure_cluster"] - - 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["azure_cluster"].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["azure_cluster"][field])): - del request_init["azure_cluster"][field][i][subfield] - else: - del request_init["azure_cluster"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_azure_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_azure_cluster_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_update_azure_cluster") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_update_azure_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.UpdateAzureClusterRequest.pb(azure_service.UpdateAzureClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = azure_service.UpdateAzureClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_azure_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_azure_cluster_rest_bad_request(request_type=azure_service.GetAzureClusterRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_azure_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureClusterRequest, - dict, -]) -def test_get_azure_cluster_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/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 = azure_resources.AzureCluster( - name='name_value', - description='description_value', - azure_region='azure_region_value', - resource_group_id='resource_group_id_value', - azure_client='azure_client_value', - state=azure_resources.AzureCluster.State.PROVISIONING, - endpoint='endpoint_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - cluster_ca_certificate='cluster_ca_certificate_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_resources.AzureCluster.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_azure_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureCluster) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.azure_region == 'azure_region_value' - assert response.resource_group_id == 'resource_group_id_value' - assert response.azure_client == 'azure_client_value' - assert response.state == azure_resources.AzureCluster.State.PROVISIONING - assert response.endpoint == 'endpoint_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_azure_cluster_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_cluster") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.GetAzureClusterRequest.pb(azure_service.GetAzureClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_resources.AzureCluster.to_json(azure_resources.AzureCluster()) - req.return_value.content = return_value - - request = azure_service.GetAzureClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_resources.AzureCluster() - - client.get_azure_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_azure_clusters_rest_bad_request(request_type=azure_service.ListAzureClustersRequest): - client = AzureClustersClient( - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_azure_clusters(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.ListAzureClustersRequest, - dict, -]) -def test_list_azure_clusters_rest_call_success(request_type): - client = AzureClustersClient( - 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 = azure_service.ListAzureClustersResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_service.ListAzureClustersResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_azure_clusters(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAzureClustersPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_azure_clusters_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_list_azure_clusters") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_list_azure_clusters") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.ListAzureClustersRequest.pb(azure_service.ListAzureClustersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_service.ListAzureClustersResponse.to_json(azure_service.ListAzureClustersResponse()) - req.return_value.content = return_value - - request = azure_service.ListAzureClustersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_service.ListAzureClustersResponse() - - client.list_azure_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_azure_cluster_rest_bad_request(request_type=azure_service.DeleteAzureClusterRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_azure_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.DeleteAzureClusterRequest, - dict, -]) -def test_delete_azure_cluster_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_azure_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_azure_cluster_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_delete_azure_cluster") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_delete_azure_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.DeleteAzureClusterRequest.pb(azure_service.DeleteAzureClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = azure_service.DeleteAzureClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_azure_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_azure_cluster_agent_token_rest_bad_request(request_type=azure_service.GenerateAzureClusterAgentTokenRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.generate_azure_cluster_agent_token(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GenerateAzureClusterAgentTokenRequest, - dict, -]) -def test_generate_azure_cluster_agent_token_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = azure_service.GenerateAzureClusterAgentTokenResponse( - access_token='access_token_value', - expires_in=1078, - token_type='token_type_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_service.GenerateAzureClusterAgentTokenResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.generate_azure_cluster_agent_token(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_service.GenerateAzureClusterAgentTokenResponse) - assert response.access_token == 'access_token_value' - assert response.expires_in == 1078 - assert response.token_type == 'token_type_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_azure_cluster_agent_token_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_generate_azure_cluster_agent_token") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_generate_azure_cluster_agent_token") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.GenerateAzureClusterAgentTokenRequest.pb(azure_service.GenerateAzureClusterAgentTokenRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_service.GenerateAzureClusterAgentTokenResponse.to_json(azure_service.GenerateAzureClusterAgentTokenResponse()) - req.return_value.content = return_value - - request = azure_service.GenerateAzureClusterAgentTokenRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_service.GenerateAzureClusterAgentTokenResponse() - - client.generate_azure_cluster_agent_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_azure_access_token_rest_bad_request(request_type=azure_service.GenerateAzureAccessTokenRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.generate_azure_access_token(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GenerateAzureAccessTokenRequest, - dict, -]) -def test_generate_azure_access_token_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = azure_service.GenerateAzureAccessTokenResponse( - access_token='access_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_service.GenerateAzureAccessTokenResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.generate_azure_access_token(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_service.GenerateAzureAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_azure_access_token_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_generate_azure_access_token") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_generate_azure_access_token") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.GenerateAzureAccessTokenRequest.pb(azure_service.GenerateAzureAccessTokenRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_service.GenerateAzureAccessTokenResponse.to_json(azure_service.GenerateAzureAccessTokenResponse()) - req.return_value.content = return_value - - request = azure_service.GenerateAzureAccessTokenRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_service.GenerateAzureAccessTokenResponse() - - client.generate_azure_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_azure_node_pool_rest_bad_request(request_type=azure_service.CreateAzureNodePoolRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_azure_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.CreateAzureNodePoolRequest, - dict, -]) -def test_create_azure_node_pool_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/azureClusters/sample3'} - request_init["azure_node_pool"] = {'name': 'name_value', 'version': 'version_value', 'config': {'vm_size': 'vm_size_value', 'root_volume': {'size_gib': 844}, 'tags': {}, 'image_type': 'image_type_value', 'ssh_config': {'authorized_key': 'authorized_key_value'}, 'proxy_config': {'resource_group_id': 'resource_group_id_value', 'secret_id': 'secret_id_value'}, 'config_encryption': {'key_id': 'key_id_value', 'public_key': 'public_key_value'}, 'taints': [{'key': 'key_value', 'value': 'value_value', 'effect': 1}], 'labels': {}}, 'subnet_id': 'subnet_id_value', 'autoscaling': {'min_node_count': 1489, 'max_node_count': 1491}, 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'max_pods_constraint': {'max_pods_per_node': 1798}, 'azure_availability_zone': 'azure_availability_zone_value', 'errors': [{'message': 'message_value'}], 'management': {'auto_repair': True}} - # 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 = azure_service.CreateAzureNodePoolRequest.meta.fields["azure_node_pool"] - - 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["azure_node_pool"].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["azure_node_pool"][field])): - del request_init["azure_node_pool"][field][i][subfield] - else: - del request_init["azure_node_pool"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_azure_node_pool(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_azure_node_pool_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_create_azure_node_pool") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_create_azure_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.CreateAzureNodePoolRequest.pb(azure_service.CreateAzureNodePoolRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = azure_service.CreateAzureNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_azure_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_azure_node_pool_rest_bad_request(request_type=azure_service.UpdateAzureNodePoolRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'azure_node_pool': {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_azure_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.UpdateAzureNodePoolRequest, - dict, -]) -def test_update_azure_node_pool_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'azure_node_pool': {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'}} - request_init["azure_node_pool"] = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4', 'version': 'version_value', 'config': {'vm_size': 'vm_size_value', 'root_volume': {'size_gib': 844}, 'tags': {}, 'image_type': 'image_type_value', 'ssh_config': {'authorized_key': 'authorized_key_value'}, 'proxy_config': {'resource_group_id': 'resource_group_id_value', 'secret_id': 'secret_id_value'}, 'config_encryption': {'key_id': 'key_id_value', 'public_key': 'public_key_value'}, 'taints': [{'key': 'key_value', 'value': 'value_value', 'effect': 1}], 'labels': {}}, 'subnet_id': 'subnet_id_value', 'autoscaling': {'min_node_count': 1489, 'max_node_count': 1491}, 'state': 1, 'uid': 'uid_value', 'reconciling': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value', 'annotations': {}, 'max_pods_constraint': {'max_pods_per_node': 1798}, 'azure_availability_zone': 'azure_availability_zone_value', 'errors': [{'message': 'message_value'}], 'management': {'auto_repair': True}} - # 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 = azure_service.UpdateAzureNodePoolRequest.meta.fields["azure_node_pool"] - - 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["azure_node_pool"].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["azure_node_pool"][field])): - del request_init["azure_node_pool"][field][i][subfield] - else: - del request_init["azure_node_pool"][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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_azure_node_pool(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_azure_node_pool_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_update_azure_node_pool") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_update_azure_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.UpdateAzureNodePoolRequest.pb(azure_service.UpdateAzureNodePoolRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = azure_service.UpdateAzureNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_azure_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_azure_node_pool_rest_bad_request(request_type=azure_service.GetAzureNodePoolRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_azure_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureNodePoolRequest, - dict, -]) -def test_get_azure_node_pool_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = azure_resources.AzureNodePool( - name='name_value', - version='version_value', - subnet_id='subnet_id_value', - state=azure_resources.AzureNodePool.State.PROVISIONING, - uid='uid_value', - reconciling=True, - etag='etag_value', - azure_availability_zone='azure_availability_zone_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_resources.AzureNodePool.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_azure_node_pool(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureNodePool) - assert response.name == 'name_value' - assert response.version == 'version_value' - assert response.subnet_id == 'subnet_id_value' - assert response.state == azure_resources.AzureNodePool.State.PROVISIONING - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.azure_availability_zone == 'azure_availability_zone_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_azure_node_pool_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_node_pool") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.GetAzureNodePoolRequest.pb(azure_service.GetAzureNodePoolRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_resources.AzureNodePool.to_json(azure_resources.AzureNodePool()) - req.return_value.content = return_value - - request = azure_service.GetAzureNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_resources.AzureNodePool() - - client.get_azure_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_azure_node_pools_rest_bad_request(request_type=azure_service.ListAzureNodePoolsRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_azure_node_pools(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.ListAzureNodePoolsRequest, - dict, -]) -def test_list_azure_node_pools_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/azureClusters/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 = azure_service.ListAzureNodePoolsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_service.ListAzureNodePoolsResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_azure_node_pools(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAzureNodePoolsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_azure_node_pools_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_list_azure_node_pools") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_list_azure_node_pools") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.ListAzureNodePoolsRequest.pb(azure_service.ListAzureNodePoolsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_service.ListAzureNodePoolsResponse.to_json(azure_service.ListAzureNodePoolsResponse()) - req.return_value.content = return_value - - request = azure_service.ListAzureNodePoolsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_service.ListAzureNodePoolsResponse() - - client.list_azure_node_pools(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_azure_node_pool_rest_bad_request(request_type=azure_service.DeleteAzureNodePoolRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_azure_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.DeleteAzureNodePoolRequest, - dict, -]) -def test_delete_azure_node_pool_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureClusters/sample3/azureNodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_azure_node_pool(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_azure_node_pool_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_delete_azure_node_pool") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_delete_azure_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.DeleteAzureNodePoolRequest.pb(azure_service.DeleteAzureNodePoolRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = azure_service.DeleteAzureNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_azure_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_azure_open_id_config_rest_bad_request(request_type=azure_service.GetAzureOpenIdConfigRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_azure_open_id_config(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureOpenIdConfigRequest, - dict, -]) -def test_get_azure_open_id_config_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = azure_resources.AzureOpenIdConfig( - issuer='issuer_value', - jwks_uri='jwks_uri_value', - response_types_supported=['response_types_supported_value'], - subject_types_supported=['subject_types_supported_value'], - id_token_signing_alg_values_supported=['id_token_signing_alg_values_supported_value'], - claims_supported=['claims_supported_value'], - grant_types=['grant_types_value'], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_resources.AzureOpenIdConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_azure_open_id_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureOpenIdConfig) - assert response.issuer == 'issuer_value' - assert response.jwks_uri == 'jwks_uri_value' - assert response.response_types_supported == ['response_types_supported_value'] - assert response.subject_types_supported == ['subject_types_supported_value'] - assert response.id_token_signing_alg_values_supported == ['id_token_signing_alg_values_supported_value'] - assert response.claims_supported == ['claims_supported_value'] - assert response.grant_types == ['grant_types_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_azure_open_id_config_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_open_id_config") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_open_id_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.GetAzureOpenIdConfigRequest.pb(azure_service.GetAzureOpenIdConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_resources.AzureOpenIdConfig.to_json(azure_resources.AzureOpenIdConfig()) - req.return_value.content = return_value - - request = azure_service.GetAzureOpenIdConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_resources.AzureOpenIdConfig() - - client.get_azure_open_id_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_azure_json_web_keys_rest_bad_request(request_type=azure_service.GetAzureJsonWebKeysRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_azure_json_web_keys(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureJsonWebKeysRequest, - dict, -]) -def test_get_azure_json_web_keys_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'azure_cluster': 'projects/sample1/locations/sample2/azureClusters/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 = azure_resources.AzureJsonWebKeys( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_resources.AzureJsonWebKeys.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_azure_json_web_keys(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureJsonWebKeys) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_azure_json_web_keys_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_json_web_keys") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_json_web_keys") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.GetAzureJsonWebKeysRequest.pb(azure_service.GetAzureJsonWebKeysRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_resources.AzureJsonWebKeys.to_json(azure_resources.AzureJsonWebKeys()) - req.return_value.content = return_value - - request = azure_service.GetAzureJsonWebKeysRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_resources.AzureJsonWebKeys() - - client.get_azure_json_web_keys(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_azure_server_config_rest_bad_request(request_type=azure_service.GetAzureServerConfigRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureServerConfig'} - 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_azure_server_config(request) - - -@pytest.mark.parametrize("request_type", [ - azure_service.GetAzureServerConfigRequest, - dict, -]) -def test_get_azure_server_config_rest_call_success(request_type): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/azureServerConfig'} - 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 = azure_resources.AzureServerConfig( - name='name_value', - supported_azure_regions=['supported_azure_regions_value'], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = azure_resources.AzureServerConfig.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_azure_server_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, azure_resources.AzureServerConfig) - assert response.name == 'name_value' - assert response.supported_azure_regions == ['supported_azure_regions_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_azure_server_config_rest_interceptors(null_interceptor): - transport = transports.AzureClustersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AzureClustersRestInterceptor(), - ) - client = AzureClustersClient(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.AzureClustersRestInterceptor, "post_get_azure_server_config") as post, \ - mock.patch.object(transports.AzureClustersRestInterceptor, "pre_get_azure_server_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = azure_service.GetAzureServerConfigRequest.pb(azure_service.GetAzureServerConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = azure_resources.AzureServerConfig.to_json(azure_resources.AzureServerConfig()) - req.return_value.content = return_value - - request = azure_service.GetAzureServerConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = azure_resources.AzureServerConfig() - - client.get_azure_server_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = AzureClustersClient( - 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(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 = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - 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(request_type=operations_pb2.DeleteOperationRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = AzureClustersClient( - 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(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 = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - 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(request_type=operations_pb2.GetOperationRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = AzureClustersClient( - 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(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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - 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(request_type=operations_pb2.ListOperationsRequest): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - 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() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = AzureClustersClient( - 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(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 = mock.Mock() - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_initialize_client_w_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_azure_client_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_client), - '__call__') as call: - client.create_azure_client(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.CreateAzureClientRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_client_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_client), - '__call__') as call: - client.get_azure_client(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureClientRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_azure_clients_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clients), - '__call__') as call: - client.list_azure_clients(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.ListAzureClientsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_azure_client_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_client), - '__call__') as call: - client.delete_azure_client(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.DeleteAzureClientRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_azure_cluster_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_cluster), - '__call__') as call: - client.create_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.CreateAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_azure_cluster_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_cluster), - '__call__') as call: - client.update_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.UpdateAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_cluster_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_cluster), - '__call__') as call: - client.get_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_azure_clusters_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_clusters), - '__call__') as call: - client.list_azure_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.ListAzureClustersRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_azure_cluster_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_cluster), - '__call__') as call: - client.delete_azure_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.DeleteAzureClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_azure_cluster_agent_token_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_cluster_agent_token), - '__call__') as call: - client.generate_azure_cluster_agent_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GenerateAzureClusterAgentTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_azure_access_token_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_azure_access_token), - '__call__') as call: - client.generate_azure_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GenerateAzureAccessTokenRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_azure_node_pool_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_azure_node_pool), - '__call__') as call: - client.create_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.CreateAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_azure_node_pool_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_azure_node_pool), - '__call__') as call: - client.update_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.UpdateAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_node_pool_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_node_pool), - '__call__') as call: - client.get_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_azure_node_pools_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_azure_node_pools), - '__call__') as call: - client.list_azure_node_pools(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.ListAzureNodePoolsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_azure_node_pool_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_azure_node_pool), - '__call__') as call: - client.delete_azure_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.DeleteAzureNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_open_id_config_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_open_id_config), - '__call__') as call: - client.get_azure_open_id_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureOpenIdConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_json_web_keys_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_json_web_keys), - '__call__') as call: - client.get_azure_json_web_keys(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureJsonWebKeysRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_azure_server_config_empty_call_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_azure_server_config), - '__call__') as call: - client.get_azure_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = azure_service.GetAzureServerConfigRequest() - - assert args[0] == request_msg - - -def test_azure_clusters_rest_lro_client(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have an 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 - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AzureClustersGrpcTransport, - ) - -def test_azure_clusters_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AzureClustersTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_azure_clusters_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.gke_multicloud_v1.services.azure_clusters.transports.AzureClustersTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AzureClustersTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_azure_client', - 'get_azure_client', - 'list_azure_clients', - 'delete_azure_client', - 'create_azure_cluster', - 'update_azure_cluster', - 'get_azure_cluster', - 'list_azure_clusters', - 'delete_azure_cluster', - 'generate_azure_cluster_agent_token', - 'generate_azure_access_token', - 'create_azure_node_pool', - 'update_azure_node_pool', - 'get_azure_node_pool', - 'list_azure_node_pools', - 'delete_azure_node_pool', - 'get_azure_open_id_config', - 'get_azure_json_web_keys', - 'get_azure_server_config', - '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_azure_clusters_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.gke_multicloud_v1.services.azure_clusters.transports.AzureClustersTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AzureClustersTransport( - 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_azure_clusters_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.gke_multicloud_v1.services.azure_clusters.transports.AzureClustersTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AzureClustersTransport() - adc.assert_called_once() - - -def test_azure_clusters_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) - AzureClustersClient() - 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.AzureClustersGrpcTransport, - transports.AzureClustersGrpcAsyncIOTransport, - ], -) -def test_azure_clusters_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.AzureClustersGrpcTransport, - transports.AzureClustersGrpcAsyncIOTransport, - transports.AzureClustersRestTransport, - ], -) -def test_azure_clusters_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.AzureClustersGrpcTransport, grpc_helpers), - (transports.AzureClustersGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_azure_clusters_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( - "gkemulticloud.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="gkemulticloud.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AzureClustersGrpcTransport, transports.AzureClustersGrpcAsyncIOTransport]) -def test_azure_clusters_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_azure_clusters_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.AzureClustersRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_azure_clusters_host_no_port(transport_name): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'gkemulticloud.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://gkemulticloud.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_azure_clusters_host_with_port(transport_name): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='gkemulticloud.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'gkemulticloud.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://gkemulticloud.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_azure_clusters_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AzureClustersClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AzureClustersClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_azure_client._session - session2 = client2.transport.create_azure_client._session - assert session1 != session2 - session1 = client1.transport.get_azure_client._session - session2 = client2.transport.get_azure_client._session - assert session1 != session2 - session1 = client1.transport.list_azure_clients._session - session2 = client2.transport.list_azure_clients._session - assert session1 != session2 - session1 = client1.transport.delete_azure_client._session - session2 = client2.transport.delete_azure_client._session - assert session1 != session2 - session1 = client1.transport.create_azure_cluster._session - session2 = client2.transport.create_azure_cluster._session - assert session1 != session2 - session1 = client1.transport.update_azure_cluster._session - session2 = client2.transport.update_azure_cluster._session - assert session1 != session2 - session1 = client1.transport.get_azure_cluster._session - session2 = client2.transport.get_azure_cluster._session - assert session1 != session2 - session1 = client1.transport.list_azure_clusters._session - session2 = client2.transport.list_azure_clusters._session - assert session1 != session2 - session1 = client1.transport.delete_azure_cluster._session - session2 = client2.transport.delete_azure_cluster._session - assert session1 != session2 - session1 = client1.transport.generate_azure_cluster_agent_token._session - session2 = client2.transport.generate_azure_cluster_agent_token._session - assert session1 != session2 - session1 = client1.transport.generate_azure_access_token._session - session2 = client2.transport.generate_azure_access_token._session - assert session1 != session2 - session1 = client1.transport.create_azure_node_pool._session - session2 = client2.transport.create_azure_node_pool._session - assert session1 != session2 - session1 = client1.transport.update_azure_node_pool._session - session2 = client2.transport.update_azure_node_pool._session - assert session1 != session2 - session1 = client1.transport.get_azure_node_pool._session - session2 = client2.transport.get_azure_node_pool._session - assert session1 != session2 - session1 = client1.transport.list_azure_node_pools._session - session2 = client2.transport.list_azure_node_pools._session - assert session1 != session2 - session1 = client1.transport.delete_azure_node_pool._session - session2 = client2.transport.delete_azure_node_pool._session - assert session1 != session2 - session1 = client1.transport.get_azure_open_id_config._session - session2 = client2.transport.get_azure_open_id_config._session - assert session1 != session2 - session1 = client1.transport.get_azure_json_web_keys._session - session2 = client2.transport.get_azure_json_web_keys._session - assert session1 != session2 - session1 = client1.transport.get_azure_server_config._session - session2 = client2.transport.get_azure_server_config._session - assert session1 != session2 -def test_azure_clusters_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AzureClustersGrpcTransport( - 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_azure_clusters_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AzureClustersGrpcAsyncIOTransport( - 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.AzureClustersGrpcTransport, transports.AzureClustersGrpcAsyncIOTransport]) -def test_azure_clusters_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.AzureClustersGrpcTransport, transports.AzureClustersGrpcAsyncIOTransport]) -def test_azure_clusters_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_azure_clusters_grpc_lro_client(): - client = AzureClustersClient( - 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_azure_clusters_grpc_lro_async_client(): - client = AzureClustersAsyncClient( - 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_azure_client_path(): - project = "squid" - location = "clam" - azure_client = "whelk" - expected = "projects/{project}/locations/{location}/azureClients/{azure_client}".format(project=project, location=location, azure_client=azure_client, ) - actual = AzureClustersClient.azure_client_path(project, location, azure_client) - assert expected == actual - - -def test_parse_azure_client_path(): - expected = { - "project": "octopus", - "location": "oyster", - "azure_client": "nudibranch", - } - path = AzureClustersClient.azure_client_path(**expected) - - # Check that the path construction is reversible. - actual = AzureClustersClient.parse_azure_client_path(path) - assert expected == actual - -def test_azure_cluster_path(): - project = "cuttlefish" - location = "mussel" - azure_cluster = "winkle" - expected = "projects/{project}/locations/{location}/azureClusters/{azure_cluster}".format(project=project, location=location, azure_cluster=azure_cluster, ) - actual = AzureClustersClient.azure_cluster_path(project, location, azure_cluster) - assert expected == actual - - -def test_parse_azure_cluster_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "azure_cluster": "abalone", - } - path = AzureClustersClient.azure_cluster_path(**expected) - - # Check that the path construction is reversible. - actual = AzureClustersClient.parse_azure_cluster_path(path) - assert expected == actual - -def test_azure_node_pool_path(): - project = "squid" - location = "clam" - azure_cluster = "whelk" - azure_node_pool = "octopus" - expected = "projects/{project}/locations/{location}/azureClusters/{azure_cluster}/azureNodePools/{azure_node_pool}".format(project=project, location=location, azure_cluster=azure_cluster, azure_node_pool=azure_node_pool, ) - actual = AzureClustersClient.azure_node_pool_path(project, location, azure_cluster, azure_node_pool) - assert expected == actual - - -def test_parse_azure_node_pool_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "azure_cluster": "cuttlefish", - "azure_node_pool": "mussel", - } - path = AzureClustersClient.azure_node_pool_path(**expected) - - # Check that the path construction is reversible. - actual = AzureClustersClient.parse_azure_node_pool_path(path) - assert expected == actual - -def test_azure_server_config_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}/azureServerConfig".format(project=project, location=location, ) - actual = AzureClustersClient.azure_server_config_path(project, location) - assert expected == actual - - -def test_parse_azure_server_config_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = AzureClustersClient.azure_server_config_path(**expected) - - # Check that the path construction is reversible. - actual = AzureClustersClient.parse_azure_server_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AzureClustersClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = AzureClustersClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AzureClustersClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = AzureClustersClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = AzureClustersClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AzureClustersClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AzureClustersClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = AzureClustersClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AzureClustersClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = AzureClustersClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = AzureClustersClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AzureClustersClient.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 = AzureClustersClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = AzureClustersClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AzureClustersClient.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.AzureClustersTransport, '_prep_wrapped_messages') as prep: - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AzureClustersTransport, '_prep_wrapped_messages') as prep: - transport_class = AzureClustersClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_delete_operation(transport: str = "grpc"): - client = AzureClustersClient( - 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_asyncio"): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AzureClustersClient( - 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 = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AzureClustersClient( - 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 = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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 = AzureClustersClient( - 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_asyncio"): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AzureClustersClient( - 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 = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AzureClustersClient( - 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 = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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 = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AzureClustersClient( - 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 = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AzureClustersClient( - 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 = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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 = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc_asyncio"): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), 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 = AzureClustersClient( - 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 = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = AzureClustersClient( - 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 = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - ) - # 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_transport_close_grpc(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = AzureClustersAsyncClient( - credentials=async_anonymous_credentials(), - 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_rest(): - client = AzureClustersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "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 = AzureClustersClient( - 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", [ - (AzureClustersClient, transports.AzureClustersGrpcTransport), - (AzureClustersAsyncClient, transports.AzureClustersGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud/gapic_version.py b/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud/gapic_version.py index 154fdc85726c..558c8aab67c5 100644 --- a/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud/gapic_version.py +++ b/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.17" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/gapic_version.py b/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/gapic_version.py index 154fdc85726c..558c8aab67c5 100644 --- a/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/gapic_version.py +++ b/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.17" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/types/attached_resources.py b/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/types/attached_resources.py index 516e387a4ada..72960a4d07c8 100644 --- a/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/types/attached_resources.py +++ b/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/types/attached_resources.py @@ -151,7 +151,7 @@ class AttachedCluster(proto.Message): slashes (/). See - `Tags `__ + `Tags `__ for more details on Google Cloud Platform tags. """ diff --git a/packages/google-cloud-gke-multicloud/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json b/packages/google-cloud-gke-multicloud/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json index ab895f559620..34b757edefd0 100644 --- a/packages/google-cloud-gke-multicloud/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json +++ b/packages/google-cloud-gke-multicloud/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-gke-multicloud", - "version": "0.6.17" + "version": "0.1.0" }, "snippets": [ {